library(shiny)
library(ggplot2)
library(syuzhet)
library(RColorBrewer)
library(wordcloud)

ui <- fluidPage(
  titlePanel("Análisis de Sentimientos"),
  
  sidebarLayout(
    sidebarPanel(
      textAreaInput("text", "Texto a analizar", rows = 10),
      actionButton("analyze", "Realizar análisis"),
    ),
    
    mainPanel(
      verbatimTextOutput("results"),
      plotOutput("emotion_plot"),
      plotOutput("wordcloud_plot"),  # Agregamos el lugar para el wordcloud
      plotOutput("positive_negative_pie")  # Agregamos el lugar para el gráfico de pastel
    )
  )
)

server <- function(input, output, session) {
  sentiment_df <- reactiveVal(NULL)  # Inicializamos como NULL
  
  observeEvent(input$analyze, {
    # Obtener el texto ingresado por el usuario
    text <- isolate(input$text)
    
    # Verificar si el texto está vacío o es NULL
    if (is.null(text) || text == "")
      return(NULL)
    
    # Tokenizar el texto
    words <- get_tokens(text)
    
    # Realizar el análisis de sentimientos
    sentiment_df_data <- get_nrc_sentiment(words, language = "spanish")
    sentiment_df(sentiment_df_data)  # Actualizar el objeto reactivo
  })
  
  # Crear el gráfico de emociones
  output$emotion_plot <- renderPlot({
    req(sentiment_df())  # Requiere que sentiment_df no sea NULL
    barplot(
      colSums(prop.table(sentiment_df()[, 1:8])),
      space = 0.2,
      horiz = FALSE,
      las = 1,
      cex.names = 0.7,
      col = brewer.pal(n = 8, name = "Set3"),
      main = "Análisis de Sentimientos",
      xlab = "Emociones"
    )
  })
  
  # Mostrar la secuencia de sentimientos
  output$results <- renderPrint({
    req(sentiment_df())  # Requiere que sentiment_df no sea NULL
    print("Secuencia de Sentimientos:")
    print((sentiment_df()$negative * -1) + sentiment_df()$positive)
  })
  
  # Generar y mostrar el wordcloud
  output$wordcloud_plot <- renderPlot({
    req(sentiment_df())  # Requiere que sentiment_df no sea NULL
    words <- get_tokens(isolate(input$text))
    wordcloud(words, max.words = 50, scale=c(3, 0.5), colors=brewer.pal(8, "Dark2"))
  })
  
  # Mostrar la proporción de palabras positivas y negativas en un gráfico de pastel
  output$positive_negative_pie <- renderPlot({
    req(sentiment_df())  # Requiere que sentiment_df no sea NULL
    
    # Contar palabras positivas y negativas
    positive_words <- sum(sentiment_df()$positive > 0)
    negative_words <- sum(sentiment_df()$negative > 0)
    
    # Crear un gráfico de pastel
    labels <- c("Palabras Positivas", "Palabras Negativas")
    values <- c(positive_words, negative_words)
    
    pie(values, labels = labels, col = c("green", "red"), main = "Proporción de Palabras Positivas/Negativas")
  })
}

shinyApp(ui, server)
Shiny applications not supported in static R Markdown documents