#Cargamos las librerías

library(tm) #Minería de texto.
## Loading required package: NLP
library(wordcloud) #crea un corpus para hacer el análisis de frecuencia de palabras.
## Loading required package: RColorBrewer
library(topicmodels) #extraer información y categorizar grandes conjuntos de documentos.
library(ggplot2) # Hacer vizualizaciones con la información disponible.
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:NLP':
## 
##     annotate
library(pdftools)#extraer el texto de los documentos en pdf y guardarlo en un Corpus.
## Using poppler version 23.04.0
library(tidytext) #permite realizar mineo de texto con el uso de herramientas tidy
library (dplyr) #contiene una colección de funciones para realizar operaciones de manipulación de datos comunes como: filtrar por fila, seleccionar columnas específicas, reordenar filas, añadir nuevas filas y agregar datos.
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(syuzhet) #Análisis de sentimiento

#Empezamos con el año 2021

# Ruta de la carpeta que contiene los archivos de texto
carpetayt2021 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Youtube/2021"

# Lista para almacenar el texto de cada archivo
textosyt2021 <- list()

# Recorre cada archivo en la carpeta
archivosyt2021 <- list.files(carpetayt2021, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2021 in archivosyt2021) {
  # Cargar el texto del archivo
  texto_brutoyt2021 <- tolower(readLines(archivoyt2021, warn = FALSE))
  
  # Eliminar URL
  texto_limpioyt2021 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2021)
  
  # Eliminar HTML
  texto_limpioyt2021 <- gsub("<.*?>", "", texto_limpioyt2021)
  
  # Eliminar signos de puntuación
  texto_limpioyt2021 <- gsub("[[:punct:]]", "", texto_limpioyt2021)
  
  # Agregar el texto limpio a la lista
  textosyt2021 <- c(textosyt2021, texto_limpioyt2021)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2021 <- paste(textosyt2021, collapse = " ")

# Usa directamente el texto preprocesado
todos_los_textosyt2021 <- tolower(texto_finalyt2021[[1]])

#Año 2022

# Ruta de la carpeta que contiene los archivos de texto
carpetayt2022 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Youtube/2022"

# Lista para almacenar el texto de cada archivo
textosyt2022 <- list()

# Recorre cada archivo en la carpeta
archivosyt2022 <- list.files(carpetayt2022, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2022 in archivosyt2022) {
  # Cargar el texto del archivo
  texto_brutoyt2022 <- tolower(readLines(archivoyt2022, warn = FALSE))
  
  # Eliminar URL
  texto_limpioyt2022 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2022)
  
  # Eliminar HTML
  texto_limpioyt2022 <- gsub("<.*?>", "", texto_limpioyt2022)
  
  # Eliminar signos de puntuación
  texto_limpioyt2022 <- gsub("[[:punct:]]", "", texto_limpioyt2022)
  
  # Agregar el texto limpio a la lista
  textosyt2022 <- c(textosyt2022, texto_limpioyt2022)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2022 <- paste(textosyt2022, collapse = " ")
# Usa directamente el texto preprocesado
todos_los_textosyt2022 <- tolower(texto_finalyt2022[[1]])

#Año 2023

# Ruta de la carpeta que contiene los archivos de texto
carpetayt2023 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Youtube/2023"

# Lista para almacenar el texto de cada archivo
textosyt2023 <- list()

# Recorre cada archivo en la carpeta
archivosyt2023 <- list.files(carpetayt2023, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2023 in archivosyt2023) {
  # Cargar el texto del archivo
  texto_brutoyt2023 <- tolower(readLines(archivoyt2023, warn = FALSE))
  
  # Eliminar URL
  texto_limpioyt2023 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2023)
  
  # Eliminar HTML
  texto_limpioyt2023 <- gsub("<.*?>", "", texto_limpioyt2023)
  
  # Eliminar signos de puntuación
  texto_limpioyt2023 <- gsub("[[:punct:]]", "", texto_limpioyt2023)
  
  # Agregar el texto limpio a la lista
  textosyt2023 <- c(textosyt2023, texto_limpioyt2023)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2023 <- paste(textosyt2023, collapse = " ")

# Usa directamente el texto preprocesado
todos_los_textosyt2023 <- tolower(texto_finalyt2023[[1]])

#Wordcloud y frecuencia de palabras

#2021
# Elimina stopwords 
todos_los_textosyt2021 <- removeWords(todos_los_textosyt2021, stopwords("spanish"))
palabras_eliminaryt2021 <- c("pero", "haber", "tener", "más", "ser", "casi", "uno", "todo", "él", "por", "cada", "con", "ese", "cualquiera", "donde", "desde", "do", "para", "este", "mucho", "que", "como","esto", "las", "era", "muchas", "muy", "los", "una","nos", "sobre", "gente", "nos", "sus", "mis", "mariana", "les", "eso", "sí","fue", "Mariana", "Maribel", "poco", "cuando", "algo", "estaba", "dice", "001", "pues", "entonces", "ahí", "aquí", "imtancia", "imtante", "hoy","ver", "hace", "si", "imtante", "pueb","múca","video","parte")

#Juntar todos los textos del 2021 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2021 <- gsub(paste(palabras_eliminaryt2021, collapse = "|"), "", todos_los_textosyt2021, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2021 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2021, " ")),
          min.freq = 10,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.07,  
          colors = brewer.pal(10, "Paired"))
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#2022
# Elimina stopwords 
todos_los_textosyt2022 <- removeWords(todos_los_textosyt2022, stopwords("spanish"))
palabras_eliminaryt2022 <- c("idíge", "múca", "legua", "ciol", "maera", "coidad", "cueta", "bie", "aí", "orige", "proce", "glo","viee", "oche", "fieta","así","dia","aqui")

#Juntar todos los textos del 2022 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2022 <- gsub(paste(palabras_eliminaryt2022, collapse = "|"), "", todos_los_textosyt2022, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2022 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2022, " ")),
          min.freq = 6,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.05,  
          colors = brewer.pal(10, "Paired"))
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents

## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents

#2023
# Elimina stopwords 
todos_los_textosyt2023 <- removeWords(todos_los_textosyt2023, stopwords("spanish"))
palabras_eliminaryt2023 <- c("aquí", "así", "ahí", "parte", "dice", "pues", "hacer", "dos", "igual", "hace", "sol", "día","bueno", "sé", "cada","vez","cómo","muchas","ver","tal","cosas","vamos","ser","amigos","entonces","dad","san")

#Juntar todos los textos del 2023 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2023 <- gsub(paste(palabras_eliminaryt2023, collapse = "|"), "", todos_los_textosyt2023, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2023 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2023, " ")),
          min.freq = 4,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.10,  
          colors = brewer.pal(10, "Paired"))
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents

## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents

#Análisis de tópicos

#2021
# Definir el número de tópicos
corpusyt2021 <- Corpus(VectorSource(todos_los_textosyt2021))
dtmyt2021 <- DocumentTermMatrix(corpusyt2021)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2021 <- LDA(dtmyt2021, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2021 <- tidy(lda_modelyt2021, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2021, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2021",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2022
# Definir el número de tópicos
corpusyt2022 <- Corpus(VectorSource(todos_los_textosyt2022))
dtmyt2022 <- DocumentTermMatrix(corpusyt2022)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2022 <- LDA(dtmyt2022, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2022 <- tidy(lda_modelyt2022, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2022, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2022",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2023

# Definir el número de tópicos
corpusyt2023 <- Corpus(VectorSource(todos_los_textosyt2023))
dtmyt2023 <- DocumentTermMatrix(corpusyt2023)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2023 <- LDA(dtmyt2023, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2023 <- tidy(lda_modelyt2023, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2023, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2023",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#análisis de emociones español

#2021
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2021 <- get_nrc_sentiment(todos_los_textosyt2021, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2021 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2021) <- sentimientos_espanolyt2021

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2021 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2021)), valor = colSums(puntuaciones_emocionesyt2021))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2021 <- sentimientos_dfyt2021 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2021, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2021", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2022
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2022 <- get_nrc_sentiment(todos_los_textosyt2022, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2022 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2022) <- sentimientos_espanolyt2022

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2022 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2022)), valor = colSums(puntuaciones_emocionesyt2022))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2022 <- sentimientos_dfyt2022 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2022, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2022", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2023
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2023 <- get_nrc_sentiment(todos_los_textosyt2023, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2023 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2023) <- sentimientos_espanolyt2023

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2023 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2023)), valor = colSums(puntuaciones_emocionesyt2023))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2023 <- sentimientos_dfyt2023 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2023, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2023", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

```