El Reconocimiento óptico de caracteres (OCR) es una tecnología utilizada para convertir diferentes tipos de documentos, como ímagenes, documentos impresos escaneados, fotografías de texto, archivos PDF o imagnes capturadas con una cámara, en datos editables y buscables.
La Minería de datos (TM) es el proceso de extrear información útil, patrones o conocimiento de texts no estructurados.
Consta en 3 etapas: 1. Obtener datos: El reconocimiento óptico de caracteres (OCR) es una tecnología que permite convertir imagenes de texto en texto editable. Tambíen es reconocido por extraccion de texto en imagenes 2. Explorar datos: Representación gráfica o visual de datos para su interpretación. Los métodos más comunes son: ánalisis de sentimientos, nueb de palabras y topic modeling. 3. Analisis predictivo: técnica y modelos estadisticos para predicir resultados futuros. los módelos más utilizados son el Random Forest, redes neuronales y regresion
# install.packages("cluster") #Analisis de Agrupamiento
library(cluster)
# install.packages("ggplot2") #Graficar
library(ggplot2)
# install.packages("data.table") #Manejo de muchos datos
library(data.table)
# install.packages("factoextra") #Gráfica optimización de numeros cluster
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:data.table':
##
## between, first, last
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# install.packages("rpart") #Gráfica optimización de numeros cluster
library(rpart)
# install.packages("rpart.plot") #Gráfica optimización de numeros cluster
library(rpart.plot)
# install.packages("tidyverse")
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ lubridate 1.9.4 ✔ tibble 3.3.0
## ✔ purrr 1.1.0 ✔ tidyr 1.3.1
## ✔ readr 2.1.5
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::between() masks data.table::between()
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::first() masks data.table::first()
## ✖ lubridate::hour() masks data.table::hour()
## ✖ lubridate::isoweek() masks data.table::isoweek()
## ✖ dplyr::lag() masks stats::lag()
## ✖ dplyr::last() masks data.table::last()
## ✖ lubridate::mday() masks data.table::mday()
## ✖ lubridate::minute() masks data.table::minute()
## ✖ lubridate::month() masks data.table::month()
## ✖ lubridate::quarter() masks data.table::quarter()
## ✖ lubridate::second() masks data.table::second()
## ✖ purrr::transpose() masks data.table::transpose()
## ✖ lubridate::wday() masks data.table::wday()
## ✖ lubridate::week() masks data.table::week()
## ✖ lubridate::yday() masks data.table::yday()
## ✖ lubridate::year() masks data.table::year()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# install.packages("tesseract")
library(tesseract)
# install.packages("magick")
library(magick)
## Linking to ImageMagick 6.9.12.93
## Enabled features: cairo, fontconfig, freetype, heic, lcms, pango, raw, rsvg, webp
## Disabled features: fftw, ghostscript, x11
# install.packages("officer")
library(officer)
# install.packages("pdftools")
library(pdftools)
## Using poppler version 23.04.0
# install.packages("purrr")
library(purrr)
imagen1 <- image_read("/Users/mariajoseflores/Downloads/imagen1.PNG")
texto1 <- ocr(imagen1)
texto1
## [1] "Linear regression with one variable x is also known as univariate linear regression\nor simple linear regression. Simple linear regression is used to predict a single\noutput from a single input. This is an example of supervised learning, which means\nthat the data is labeled, i.e., the output values are known in the training data. Let us\nfit a line through the data using simple linear regression as shown in Fig. 4.1.\n"
doc1 <- read_docx() #Crea documento word blanco
doc1 <- doc1 %>% body_add_par(texto1) #Pega el texto en el documento
# Extraer texto con OCR
texto1 <- ocr(imagen1)
# Crear documento Word en blanco
doc1 <- read_docx()
# Pegar el texto extraído
doc1 <- doc1 %>% body_add_par(texto1)
imagen2 <- image_read("/Users/mariajoseflores/Downloads/imagen2.PNG")
tesseract_download ("spa")
## Training data already exists. Overwriting /Users/mariajoseflores/Library/Application Support/tesseract5/tessdata/spa.traineddata
## [1] "/Users/mariajoseflores/Library/Application Support/tesseract5/tessdata/spa.traineddata"
# Descargar datos de idioma español (solo se hace una vez)
tesseract_download("spa")
## Training data already exists. Overwriting /Users/mariajoseflores/Library/Application Support/tesseract5/tessdata/spa.traineddata
## [1] "/Users/mariajoseflores/Library/Application Support/tesseract5/tessdata/spa.traineddata"
# Crear el motor en español
esp_engine <- tesseract("spa")
# Usar el motor con OCR
imagen2 <- image_read("/Users/mariajoseflores/Downloads/imagen2.PNG")
texto2 <- ocr(imagen2, engine = esp_engine)
# Crear y guardar el Word
doc2 <- read_docx() %>%
body_add_par(texto2)
print(doc2, target = "texto2.docx")
pdf_eso <- pdf_convert("/Users/mariajoseflores/Downloads/eso.pdf") %>% map(ocr)
## Converting page 1 to eso_1.png... done!
## Converting page 2 to eso_2.png... done!
texto <- pdf_eso
# Paquetes necesarios
# install.packages("syuzhet")
library(syuzhet)
library(dplyr)
# 1) Unir el texto OCR del PDF (lista -> vector de caracteres)
# pdf_eso viene de: pdf_convert(...) %>% map(ocr)
texto <- pdf_eso %>% unlist(use.names = FALSE) %>% paste(collapse = "\n")
# 2) Partir en oraciones (syuzhet)
oraciones <- get_sentences(texto)
# 3) Emociones NRC en español
# Alegría, Tristeza, Ira, Miedo, Sorpresa, Asco, Anticipación, Confianza
emociones <- get_nrc_sentiment(oraciones, language = "spanish")
# 4) Agregar por emoción y normalizar (proporciones)
emociones_prop <- prop.table(colSums(emociones[, 1:8]))
# 5) Gráfica rápida (base R)
barplot(emociones_prop,
main = "Emociones NRC (español)",
ylab = "Proporción",
las = 2)
# Si quieres ver las cifras ordenadas:
sort(emociones_prop, decreasing = TRUE)
## trust fear anticipation sadness surprise anger
## 0.20652174 0.19565217 0.17391304 0.10869565 0.09239130 0.08695652
## joy disgust
## 0.07608696 0.05978261