Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,20 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import docx
|
| 4 |
-
import fitz
|
| 5 |
import requests
|
| 6 |
import re
|
| 7 |
from fpdf import FPDF
|
| 8 |
from datetime import datetime
|
| 9 |
|
| 10 |
-
# --- CONFIGURACIÓN ---
|
| 11 |
-
st.set_page_config(page_title="Auditor Académico
|
| 12 |
|
| 13 |
-
#
|
|
|
|
| 14 |
client = InferenceClient(model="meta-llama/Meta-Llama-3-8B-Instruct")
|
| 15 |
|
| 16 |
-
# --- FUNCIONES
|
| 17 |
def extraer_texto(archivo):
|
| 18 |
try:
|
| 19 |
if archivo.name.endswith('.pdf'):
|
|
@@ -40,96 +41,86 @@ def validar_urls(texto):
|
|
| 40 |
return resultados
|
| 41 |
|
| 42 |
def analizar_auditoria(texto, estilo):
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
-
"
|
| 48 |
-
"Chicago": "Enfoque en notas al pie de página o autor-fecha, y estructura de bibliografía detallada."
|
| 49 |
}
|
| 50 |
-
|
| 51 |
prompt = f"""
|
| 52 |
-
Actúa como auditor académico experto en la norma {estilo}. {
|
| 53 |
-
Analiza el texto
|
| 54 |
-
Genera un porcentaje de cumplimiento (0-100%).
|
| 55 |
-
Devuelve los hallazgos en una tabla con: Fragmento | Error | Regla {estilo} | Sugerencia.
|
| 56 |
|
| 57 |
-
|
| 58 |
[PORCENTAJE]: X%
|
| 59 |
-
[
|
|
|
|
|
|
|
| 60 |
|
| 61 |
Texto: {texto[:4000]}
|
| 62 |
"""
|
| 63 |
try:
|
| 64 |
response = client.chat_completion(messages=[{"role": "user", "content": prompt}], max_tokens=2000)
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
except Exception as e:
|
| 67 |
-
return f"Error IA: {str(e)}"
|
| 68 |
|
| 69 |
# --- INTERFAZ ---
|
| 70 |
-
st.title("🎓 Auditor Académico
|
| 71 |
-
st.markdown("### Verificación Normativa: APA, Vancouver, MLA y Chicago")
|
| 72 |
|
| 73 |
-
# Barra lateral para configuración
|
| 74 |
with st.sidebar:
|
| 75 |
st.header("Configuración")
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
)
|
| 80 |
-
st.info(f"Auditoría configurada para: **{estilo_seleccionado}**")
|
| 81 |
|
| 82 |
-
|
| 83 |
|
| 84 |
-
if
|
| 85 |
-
texto_puro = extraer_texto(
|
| 86 |
|
| 87 |
-
if st.button(f"🚀
|
| 88 |
-
with st.spinner("Procesando..."):
|
| 89 |
-
|
| 90 |
-
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
col1, col2 = st.columns(2)
|
| 96 |
with col1:
|
| 97 |
-
st.metric(f"Cumplimiento {
|
| 98 |
-
st.markdown(
|
| 99 |
|
| 100 |
with col2:
|
| 101 |
-
st.subheader("🌐
|
| 102 |
-
|
| 103 |
-
for s in status_urls: st.write(s)
|
| 104 |
-
else: st.write("No se detectaron enlaces.")
|
| 105 |
|
| 106 |
-
# --- GENERADOR DE
|
| 107 |
try:
|
| 108 |
pdf = FPDF()
|
| 109 |
pdf.add_page()
|
| 110 |
pdf.set_font("Helvetica", 'B', 16)
|
| 111 |
-
pdf.cell(200, 10, txt=f"INFORME
|
| 112 |
pdf.set_font("Helvetica", size=10)
|
| 113 |
-
pdf.cell(200, 10, txt=f"Fecha: {datetime.now().strftime('%Y-%m-%d')}", ln=1, align='C')
|
| 114 |
-
pdf.ln(10)
|
| 115 |
|
| 116 |
-
|
| 117 |
-
pdf.
|
| 118 |
-
pdf.ln(5)
|
| 119 |
|
| 120 |
-
pdf.
|
| 121 |
-
|
| 122 |
-
pdf.multi_cell(0, 10, txt=txt_reporte)
|
| 123 |
-
|
| 124 |
-
pdf_bytes = bytes(pdf.output())
|
| 125 |
-
st.download_button(
|
| 126 |
-
label="📥 DESCARGAR INFORME PDF",
|
| 127 |
-
data=pdf_bytes,
|
| 128 |
-
file_name=f"Auditoria_{estilo_seleccionado}.pdf",
|
| 129 |
-
mime="application/pdf"
|
| 130 |
-
)
|
| 131 |
except Exception as e:
|
| 132 |
st.error(f"Error PDF: {e}")
|
| 133 |
|
| 134 |
st.divider()
|
| 135 |
-
st.caption(
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import docx
|
| 4 |
+
import fitz # PyMuPDF
|
| 5 |
import requests
|
| 6 |
import re
|
| 7 |
from fpdf import FPDF
|
| 8 |
from datetime import datetime
|
| 9 |
|
| 10 |
+
# --- CONFIGURACIÓN DE PÁGINA ---
|
| 11 |
+
st.set_page_config(page_title="Auditor Académico Pro", page_icon="🎓", layout="wide")
|
| 12 |
|
| 13 |
+
# --- CONEXIÓN IA ---
|
| 14 |
+
# Asegúrate de tener el HF_TOKEN en Settings > Secrets de tu Space
|
| 15 |
client = InferenceClient(model="meta-llama/Meta-Llama-3-8B-Instruct")
|
| 16 |
|
| 17 |
+
# --- FUNCIONES DE PROCESAMIENTO ---
|
| 18 |
def extraer_texto(archivo):
|
| 19 |
try:
|
| 20 |
if archivo.name.endswith('.pdf'):
|
|
|
|
| 41 |
return resultados
|
| 42 |
|
| 43 |
def analizar_auditoria(texto, estilo):
|
| 44 |
+
detalles = {
|
| 45 |
+
"APA 7": "Enfoque en autor-fecha, sangría francesa y DOIs.",
|
| 46 |
+
"Vancouver": "Enfoque en numeración consecutiva y estilo biomédico.",
|
| 47 |
+
"MLA 9": "Enfoque en autor-página y Works Cited.",
|
| 48 |
+
"Chicago": "Enfoque en notas al pie o bibliografía detallada."
|
|
|
|
| 49 |
}
|
| 50 |
+
|
| 51 |
prompt = f"""
|
| 52 |
+
Actúa como auditor académico experto en la norma {estilo}. {detalles[estilo]}
|
| 53 |
+
Analiza el texto SIN MODIFICARLO.
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
Responde con este formato:
|
| 56 |
[PORCENTAJE]: X%
|
| 57 |
+
[HALLAZGOS]:
|
| 58 |
+
|
| 59 |
+
| Fragmento | Error | Regla | Sugerencia |
|
| 60 |
|
| 61 |
Texto: {texto[:4000]}
|
| 62 |
"""
|
| 63 |
try:
|
| 64 |
response = client.chat_completion(messages=[{"role": "user", "content": prompt}], max_tokens=2000)
|
| 65 |
+
|
| 66 |
+
# --- SOLUCIÓN DEFINITIVA AL ERROR DE LISTA/OBJETO ---
|
| 67 |
+
if hasattr(response, 'choices'):
|
| 68 |
+
return response.choices.message.content
|
| 69 |
+
elif isinstance(response, list) and len(response) > 0:
|
| 70 |
+
# Si es una lista de mensajes, buscamos el contenido
|
| 71 |
+
return response[0].get('generated_text', str(response[0]))
|
| 72 |
+
else:
|
| 73 |
+
return str(response)
|
| 74 |
except Exception as e:
|
| 75 |
+
return f"Error en la IA: {str(e)}"
|
| 76 |
|
| 77 |
# --- INTERFAZ ---
|
| 78 |
+
st.title("🎓 Auditor Académico Pro")
|
|
|
|
| 79 |
|
|
|
|
| 80 |
with st.sidebar:
|
| 81 |
st.header("Configuración")
|
| 82 |
+
estilo = st.selectbox("Norma a auditar:", ["APA 7", "Vancouver", "MLA 9", "Chicago"])
|
| 83 |
+
st.divider()
|
| 84 |
+
st.caption("v2.1 - Actualizado Abril 2026")
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
archivo = st.file_uploader("Sube tu archivo (PDF o Word)", type=["pdf", "docx"])
|
| 87 |
|
| 88 |
+
if archivo:
|
| 89 |
+
texto_puro = extraer_texto(archivo)
|
| 90 |
|
| 91 |
+
if st.button(f"🚀 Iniciar Auditoría {estilo}"):
|
| 92 |
+
with st.spinner("Procesando datos..."):
|
| 93 |
+
informe = analizar_auditoria(texto_puro, estilo)
|
| 94 |
+
urls = validar_urls(texto_puro)
|
| 95 |
|
| 96 |
+
# Extraer porcentaje
|
| 97 |
+
p_match = re.search(r'(\d+)%', informe)
|
| 98 |
+
valor_p = p_match.group(1) if p_match else "50"
|
| 99 |
|
| 100 |
col1, col2 = st.columns(2)
|
| 101 |
with col1:
|
| 102 |
+
st.metric(f"Cumplimiento {estilo}", f"{valor_p}%")
|
| 103 |
+
st.markdown(informe)
|
| 104 |
|
| 105 |
with col2:
|
| 106 |
+
st.subheader("🌐 Estado de URLs")
|
| 107 |
+
for u in urls: st.write(u)
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
# --- GENERADOR DE PDF ---
|
| 110 |
try:
|
| 111 |
pdf = FPDF()
|
| 112 |
pdf.add_page()
|
| 113 |
pdf.set_font("Helvetica", 'B', 16)
|
| 114 |
+
pdf.cell(200, 10, txt=f"INFORME {estilo}", ln=1, align='C')
|
| 115 |
pdf.set_font("Helvetica", size=10)
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
clean_text = informe.replace('|', ' ').encode('latin-1', 'ignore').decode('latin-1')
|
| 118 |
+
pdf.multi_cell(0, 10, txt=clean_text)
|
|
|
|
| 119 |
|
| 120 |
+
pdf_output = pdf.output()
|
| 121 |
+
st.download_button("📥 Descargar PDF", bytes(pdf_output), f"Auditoria_{estilo}.pdf")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
except Exception as e:
|
| 123 |
st.error(f"Error PDF: {e}")
|
| 124 |
|
| 125 |
st.divider()
|
| 126 |
+
st.caption("Esta herramienta analiza el cumplimiento normativo sin alterar el texto original.")
|