Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ import os
|
|
| 2 |
import io
|
| 3 |
import re
|
| 4 |
import json
|
|
|
|
| 5 |
import streamlit as st
|
| 6 |
from docx import Document
|
| 7 |
from docx.shared import Cm, Pt
|
|
@@ -10,19 +11,16 @@ from pydantic import BaseModel
|
|
| 10 |
from google import genai
|
| 11 |
from google.genai import types
|
| 12 |
|
| 13 |
-
# ─── 1. CONFIGURAÇÃO
|
| 14 |
-
st.set_page_config(page_title="Corretor TCC - UNIFAGOC", page_icon="⚖
|
| 15 |
|
| 16 |
-
# Limpa o cache se o usuário trocar de arquivo, evitando downloads cruzados
|
| 17 |
def reset_estado(chave):
|
| 18 |
-
|
| 19 |
-
st.session_state[chave] = None
|
| 20 |
|
| 21 |
-
|
| 22 |
-
if
|
| 23 |
-
if "doc_formatado_bytes" not in st.session_state: st.session_state.doc_formatado_bytes = None
|
| 24 |
|
| 25 |
-
# ─── 2.
|
| 26 |
class AuditoriaTCC(BaseModel):
|
| 27 |
aderencia_percentual: int
|
| 28 |
diagnostico_geral: str
|
|
@@ -56,353 +54,235 @@ class ProblemaReferencia(BaseModel):
|
|
| 56 |
class AnaliseABNT(BaseModel):
|
| 57 |
problemas: list[ProblemaReferencia]
|
| 58 |
|
| 59 |
-
# ─── 3.
|
| 60 |
@st.cache_resource
|
| 61 |
def get_client():
|
| 62 |
-
api_key = os.environ.get("GEMINI_API_KEY")
|
| 63 |
if not api_key:
|
| 64 |
-
st.error("❌ ERRO:
|
| 65 |
st.stop()
|
| 66 |
return genai.Client(api_key=api_key)
|
| 67 |
|
| 68 |
client = get_client()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
# ─── 4. MANIPULAÇÃO AVANÇADA DE DOCUMENTOS (DOCX) ─────────────────────────
|
| 71 |
def extrair_texto_docx(arquivo_upload) -> str:
|
| 72 |
-
|
| 73 |
-
return "\n\n".join([para.text.strip() for para in doc.paragraphs if para.text.strip()])
|
| 74 |
|
| 75 |
def docx_to_bytes(doc: Document) -> bytes:
|
| 76 |
-
|
| 77 |
-
doc.save(byte_io)
|
| 78 |
-
return byte_io.getvalue()
|
| 79 |
|
| 80 |
def estimar_paginas(doc: Document) -> int:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
if not re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS", para.text, re.IGNORECASE)
|
| 84 |
-
)
|
| 85 |
-
return max(1, palavras_totais // 350)
|
| 86 |
|
| 87 |
-
def _set_run_font(run, nome
|
| 88 |
-
run.font.name = nome
|
| 89 |
-
run.font.size = Pt(tamanho_pt)
|
| 90 |
if negrito is not None: run.font.bold = negrito
|
| 91 |
if italico is not None: run.font.italic = italico
|
| 92 |
|
| 93 |
def substituir_texto_cross_run(para, original, corrigido) -> int:
|
| 94 |
-
"""Substitui textos mesmo quando fragmentados em múltiplos runs pelo Word."""
|
| 95 |
if original not in para.text: return 0
|
| 96 |
-
|
| 97 |
-
# Se está num único run (caso simples)
|
| 98 |
for run in para.runs:
|
| 99 |
if original in run.text:
|
| 100 |
run.text = run.text.replace(original, corrigido, 1)
|
| 101 |
return 1
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
texto_completo = para.text.replace(original, corrigido, 1)
|
| 106 |
para.clear()
|
| 107 |
-
|
| 108 |
-
if
|
|
|
|
| 109 |
return 1
|
| 110 |
|
| 111 |
def formatacao_cruzada_indices(para, texto_alvo, aplicar_italico=False, aplicar_negrito=False) -> int:
|
| 112 |
-
|
| 113 |
if aplicar_italico:
|
| 114 |
-
matches = list(re.finditer(r'\b' + re.escape(texto_alvo) + r'\b', para.text, re.
|
| 115 |
else:
|
| 116 |
idx = para.text.find(texto_alvo)
|
| 117 |
-
matches = [(idx, idx
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
pos_atual = 0
|
| 123 |
for run in para.runs:
|
| 124 |
-
fim_run =
|
| 125 |
-
if
|
| 126 |
if aplicar_italico: run.italic = True
|
| 127 |
if aplicar_negrito: run.bold = True
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
return
|
| 131 |
|
| 132 |
def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
| 133 |
-
for
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
em_referencias, em_resumo = False, False
|
| 140 |
|
|
|
|
| 141 |
for para in doc.paragraphs:
|
| 142 |
-
|
| 143 |
-
if not
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
elif re.match(r"^(?:INTRODU[ÇC]|ABSTRACT|1[\s\.])", texto, re.IGNORECASE):
|
| 150 |
-
em_resumo = False
|
| 151 |
|
| 152 |
-
|
| 153 |
-
if is_titulo_refs: em_referencias = True
|
| 154 |
-
|
| 155 |
-
# REFERÊNCIAS (Entradas)
|
| 156 |
-
if em_referencias and not is_titulo_refs:
|
| 157 |
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.LEFT, Cm(0), Cm(0)
|
| 158 |
pf.space_before, pf.space_after, pf.line_spacing = Pt(0), Pt(6), 1.0
|
| 159 |
-
for
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.CENTER, Cm(0), Cm(0)
|
| 164 |
-
pf.space_before, pf.space_after, pf.line_spacing = Pt(12), Pt(12), 1.5
|
| 165 |
-
for run in para.runs: _set_run_font(run, "Calibri", 12, negrito=True, italico=False)
|
| 166 |
-
|
| 167 |
-
# RESUMO
|
| 168 |
elif em_resumo:
|
| 169 |
-
pf.alignment
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
elif
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
pf.space_before, pf.space_after, pf.line_spacing = Pt(0), Pt(12), 1.5
|
| 180 |
-
for run in para.runs: _set_run_font(run, "Calibri", 12, negrito=True, italico=False)
|
| 181 |
-
elif "heading 3" in style_name or "heading3" in style_name:
|
| 182 |
-
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.JUSTIFY, Cm(0), Cm(0)
|
| 183 |
-
pf.space_before, pf.space_after, pf.line_spacing = Pt(12), Pt(0), 1.5
|
| 184 |
-
for run in para.runs: _set_run_font(run, "Calibri", 12, negrito=True, italico=False)
|
| 185 |
-
elif "heading 4" in style_name or "heading4" in style_name:
|
| 186 |
-
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.JUSTIFY, Cm(0), Cm(0)
|
| 187 |
-
pf.space_before, pf.space_after, pf.line_spacing = Pt(0), Pt(0), 1.5
|
| 188 |
-
for run in para.runs: _set_run_font(run, "Calibri", 12, negrito=True, italico=True)
|
| 189 |
-
else:
|
| 190 |
-
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.CENTER, Cm(0), Cm(0)
|
| 191 |
-
pf.space_before, pf.space_after, pf.line_spacing = Pt(6), Pt(12), 1.5
|
| 192 |
-
for run in para.runs: _set_run_font(run, "Calibri", 14, negrito=True, italico=False)
|
| 193 |
-
|
| 194 |
-
# CITAÇÕES LONGAS
|
| 195 |
-
elif pf.left_indent is not None and pf.left_indent >= Cm(3.5):
|
| 196 |
-
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.JUSTIFY, Cm(0), Cm(4.0)
|
| 197 |
-
pf.space_before, pf.space_after, pf.line_spacing = Pt(6), Pt(6), 1.0
|
| 198 |
-
for run in para.runs: _set_run_font(run, "Calibri", 11)
|
| 199 |
-
|
| 200 |
-
# CORPO DO TEXTO
|
| 201 |
else:
|
| 202 |
-
pf.alignment
|
| 203 |
-
|
| 204 |
-
for run in para.runs: _set_run_font(run, "Calibri", 12)
|
| 205 |
|
| 206 |
-
# ─── 5. INTERFACE
|
| 207 |
-
st.title("⚖
|
| 208 |
-
aba_auditoria, aba_revisao, aba_abnt = st.tabs([
|
| 209 |
-
"🔍 Auditoria
|
| 210 |
-
"🧠 Revisão Textual Inteligente",
|
| 211 |
-
"📐 Formatação Total ABNT"
|
| 212 |
])
|
| 213 |
|
| 214 |
-
#
|
| 215 |
-
# ABA 1: AUDITORIA E PONTUAÇÃO UNIFAGOC
|
| 216 |
-
# ==============================================================================
|
| 217 |
with aba_auditoria:
|
| 218 |
-
st.markdown("Cruze
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
with
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
texto_projeto = extrair_texto_docx(arq_projeto)
|
| 232 |
-
texto_tcc = extrair_texto_docx(arq_tcc)
|
| 233 |
-
|
| 234 |
-
regra_fase = "ATENÇÃO: O aluno está em TCC 1. NÃO penalize a ausência de Resumo e Conclusão." if "TCC 1" in fase_tcc else "O aluno está em TCC 2. Exija o trabalho completo."
|
| 235 |
-
prompt = (
|
| 236 |
-
f"Como Professor Examinador titular da banca de Direito da UNIFAGOC:\n{regra_fase}\n"
|
| 237 |
-
f"=== PRÉ-PROJETO ===\n{texto_projeto}\n=== TCC ===\n{texto_tcc}\n"
|
| 238 |
-
"TAREFA 1: Avalie o cruzamento de dados, fuga de tema e objetivos.\n"
|
| 239 |
-
"TAREFA 2: Distribua 80 pontos rigorosamente de acordo com os critérios da ficha UNIFAGOC."
|
| 240 |
-
)
|
| 241 |
-
|
| 242 |
-
st.write("A submeter dados à IA do Google...")
|
| 243 |
try:
|
| 244 |
-
res = client.models.generate_content(
|
| 245 |
-
|
| 246 |
-
config=types.GenerateContentConfig(temperature=0.0, response_mime_type="application/json", response_schema=AuditoriaTCC)
|
| 247 |
-
)
|
| 248 |
st.session_state.resultado_auditoria = json.loads(res.text)
|
| 249 |
-
|
| 250 |
-
except Exception as e:
|
| 251 |
-
|
| 252 |
-
st.error(f"Erro: {e}")
|
| 253 |
|
| 254 |
if st.session_state.resultado_auditoria:
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
st.info(f"**NOTA FINAL TEXTUAL: {nota_total}/80 pontos**\n*Parecer da Banca:* {dados.get('justificativa_notas_banca')}")
|
| 266 |
-
st.divider()
|
| 267 |
-
|
| 268 |
-
st.metric("Índice de Aderência ao Projeto", f"{dados.get('aderencia_percentual')}%")
|
| 269 |
-
col_a, col_b = st.columns(2)
|
| 270 |
-
with col_a:
|
| 271 |
-
st.subheader("🎯 Problema de Pesquisa")
|
| 272 |
-
if dados.get("tcc_respondeu_ao_problema"): st.success(f"✅ O TCC respondeu: {dados.get('justificativa_problema')}")
|
| 273 |
-
else: st.error(f"❌ Não respondeu: {dados.get('justificativa_problema')}")
|
| 274 |
-
with col_b:
|
| 275 |
-
st.subheader("📋 Objetivos")
|
| 276 |
-
for f in dados.get("objetivos_nao_cumpridos_no_tcc", []): st.error(f"Faltou: {f}")
|
| 277 |
-
if not dados.get("objetivos_nao_cumpridos_no_tcc"): st.success("✅ Todos os objetivos foram abordados.")
|
| 278 |
-
|
| 279 |
-
st.subheader("🚨 Filtro Anti-Embromação")
|
| 280 |
-
for fuga in dados.get("desvios_de_tema_ou_linguica", []): st.warning(f"Fuga: {fuga}")
|
| 281 |
-
for ia in dados.get("indicios_texto_generico_ia", []): st.error(f"Indício de IA/Texto Genérico: {ia}")
|
| 282 |
-
|
| 283 |
-
# ==============================================================================
|
| 284 |
-
# ABA 2: REVISÃO TEXTUAL INTELIGENTE
|
| 285 |
-
# ==============================================================================
|
| 286 |
with aba_revisao:
|
| 287 |
-
st.markdown("
|
| 288 |
-
arq_rev = st.file_uploader("
|
| 289 |
-
|
| 290 |
-
if st.button("🧠 Realizar Revisão"):
|
| 291 |
if arq_rev:
|
| 292 |
-
with st.
|
| 293 |
-
st.write("A ler o documento completo...")
|
| 294 |
texto = extrair_texto_docx(arq_rev)
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
)
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
dados = json.loads(res.text)
|
| 308 |
-
|
| 309 |
-
st.write("A aplicar correções cirúrgicas no Word...")
|
| 310 |
-
doc_rev = Document(arq_rev)
|
| 311 |
-
aplicadas_texto, aplicadas_italico = 0, 0
|
| 312 |
-
|
| 313 |
-
if dados.get("correcoes"):
|
| 314 |
-
for c in dados["correcoes"]:
|
| 315 |
-
for para in doc_rev.paragraphs:
|
| 316 |
-
aplicadas_texto += substituir_texto_cross_run(para, c["original"], c["corrigido"])
|
| 317 |
-
|
| 318 |
-
if dados.get("termos_estrangeiros_para_italico"):
|
| 319 |
-
for termo in dados["termos_estrangeiros_para_italico"]:
|
| 320 |
-
for para in doc_rev.paragraphs:
|
| 321 |
-
aplicadas_italico += formatacao_cruzada_indices(para, termo, aplicar_italico=True)
|
| 322 |
-
|
| 323 |
-
st.session_state.doc_revisado_bytes = docx_to_bytes(doc_rev)
|
| 324 |
-
st.session_state.nome_arq_rev = f"{arq_rev.name.replace('.docx', '')}_Revisado.docx"
|
| 325 |
-
status.update(label=f"Processo finalizado com {aplicadas_texto + aplicadas_italico} intervenções automáticas.", state="complete", expanded=False)
|
| 326 |
-
except Exception as e:
|
| 327 |
-
status.update(label="Erro no processamento.", state="error")
|
| 328 |
-
st.error(f"Erro: {e}")
|
| 329 |
-
|
| 330 |
if st.session_state.doc_revisado_bytes:
|
| 331 |
-
st.download_button(
|
| 332 |
-
"⬇️ Baixar TCC Revisado (.docx)",
|
| 333 |
-
data=st.session_state.doc_revisado_bytes,
|
| 334 |
-
file_name=st.session_state.nome_arq_rev,
|
| 335 |
-
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
| 336 |
-
)
|
| 337 |
|
| 338 |
-
#
|
| 339 |
-
# ABA 3: FORMATAÇÃO TOTAL ABNT (UNIFAGOC)
|
| 340 |
-
# ==============================================================================
|
| 341 |
with aba_abnt:
|
| 342 |
-
st.markdown("
|
| 343 |
-
arq_abnt = st.file_uploader("
|
| 344 |
-
|
| 345 |
-
if st.button("📐 Formatar TCC"):
|
| 346 |
if arq_abnt:
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
st.session_state.nome_arq_abnt = f"{arq_abnt.name.replace('.docx', '')}_Formatado.docx"
|
| 369 |
-
|
| 370 |
-
if refs_limpas:
|
| 371 |
-
texto_refs = "\n".join(f"[{idx}] {txt}" for idx, txt in refs_limpas)
|
| 372 |
-
prompt_abnt = (
|
| 373 |
-
"Analise as referências (ABNT 6023:2018). Para cada uma, devolva o índice exato entre colchetes como 'numero', "
|
| 374 |
-
"e extraia o trecho EXATO (título do livro ou nome da revista/periódico) que deve receber negrito.\n"
|
| 375 |
-
f"REFERÊNCIAS:\n{texto_refs}"
|
| 376 |
-
)
|
| 377 |
-
try:
|
| 378 |
-
res = client.models.generate_content(
|
| 379 |
-
model="gemini-3.5-flash", contents=prompt_abnt,
|
| 380 |
-
config=types.GenerateContentConfig(temperature=0.0, response_mime_type="application/json", response_schema=AnaliseABNT)
|
| 381 |
-
)
|
| 382 |
-
dados_abnt = json.loads(res.text)
|
| 383 |
-
|
| 384 |
-
mapa_idx_para = {idx: doc_abnt.paragraphs[idx] for idx, _ in refs_limpas if idx < len(doc_abnt.paragraphs)}
|
| 385 |
-
negs_aplicados = 0
|
| 386 |
-
|
| 387 |
-
for problema in dados_abnt.get("problemas", []):
|
| 388 |
-
num, elem = problema.get("numero"), problema.get("elemento_negrito", "").strip()
|
| 389 |
-
if elem and num in mapa_idx_para:
|
| 390 |
-
negs_aplicados += formatacao_cruzada_indices(mapa_idx_para[num], elem, aplicar_negrito=True)
|
| 391 |
-
|
| 392 |
-
st.session_state.doc_formatado_bytes = docx_to_bytes(doc_abnt)
|
| 393 |
-
status.update(label=f"TCC formatado! {negs_aplicados} negritos aplicados nas referências.", state="complete", expanded=False)
|
| 394 |
-
except Exception as e:
|
| 395 |
-
st.session_state.doc_formatado_bytes = docx_to_bytes(doc_abnt)
|
| 396 |
-
status.update(label="Formatação aplicada (negrito de referências ignorado).", state="complete")
|
| 397 |
-
st.warning(f"Aviso na análise ABNT: {e}")
|
| 398 |
-
else:
|
| 399 |
-
st.session_state.doc_formatado_bytes = docx_to_bytes(doc_abnt)
|
| 400 |
-
status.update(label="Formatação aplicada (nenhuma referência encontrada).", state="complete")
|
| 401 |
-
|
| 402 |
if st.session_state.doc_formatado_bytes:
|
| 403 |
-
st.download_button(
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import io
|
| 3 |
import re
|
| 4 |
import json
|
| 5 |
+
import zipfile
|
| 6 |
import streamlit as st
|
| 7 |
from docx import Document
|
| 8 |
from docx.shared import Cm, Pt
|
|
|
|
| 11 |
from google import genai
|
| 12 |
from google.genai import types
|
| 13 |
|
| 14 |
+
# ─── 1. CONFIGURAÇÃO ───────────────────────────────────
|
| 15 |
+
st.set_page_config(page_title="Corretor TCC - UNIFAGOC", page_icon="⚖", layout="wide")
|
| 16 |
|
|
|
|
| 17 |
def reset_estado(chave):
|
| 18 |
+
st.session_state.pop(chave, None)
|
|
|
|
| 19 |
|
| 20 |
+
for k in ["resultado_auditoria","doc_revisado_bytes","doc_formatado_bytes","nome_arq_rev","nome_arq_abnt"]:
|
| 21 |
+
if k not in st.session_state: st.session_state[k] = None
|
|
|
|
| 22 |
|
| 23 |
+
# ─── 2. SCHEMAS ────────────────────────────────────────
|
| 24 |
class AuditoriaTCC(BaseModel):
|
| 25 |
aderencia_percentual: int
|
| 26 |
diagnostico_geral: str
|
|
|
|
| 54 |
class AnaliseABNT(BaseModel):
|
| 55 |
problemas: list[ProblemaReferencia]
|
| 56 |
|
| 57 |
+
# ─── 3. CLIENTE GEMINI ─────────────────────────────────
|
| 58 |
@st.cache_resource
|
| 59 |
def get_client():
|
| 60 |
+
api_key = st.secrets.get("GEMINI_API_KEY") or os.environ.get("GEMINI_API_KEY")
|
| 61 |
if not api_key:
|
| 62 |
+
st.error("❌ ERRO: GEMINI_API_KEY não encontrada nos Secrets.")
|
| 63 |
st.stop()
|
| 64 |
return genai.Client(api_key=api_key)
|
| 65 |
|
| 66 |
client = get_client()
|
| 67 |
+
MODEL = "gemini-3.5-flash"
|
| 68 |
+
|
| 69 |
+
# ─── 4. MANIPULAÇÃO DOCX ───────────────────────────────
|
| 70 |
+
@st.cache_data(show_spinner=False)
|
| 71 |
+
def _extrair_cached(file_bytes: bytes) -> str:
|
| 72 |
+
doc = Document(io.BytesIO(file_bytes))
|
| 73 |
+
return "\n\n".join([p.text.strip() for p in doc.paragraphs if p.text.strip()])
|
| 74 |
|
|
|
|
| 75 |
def extrair_texto_docx(arquivo_upload) -> str:
|
| 76 |
+
return _extrair_cached(arquivo_upload.getvalue())
|
|
|
|
| 77 |
|
| 78 |
def docx_to_bytes(doc: Document) -> bytes:
|
| 79 |
+
bio = io.BytesIO(); doc.save(bio); return bio.getvalue()
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def estimar_paginas(doc: Document) -> int:
|
| 82 |
+
palavras = sum(len(p.text.split()) for p in doc.paragraphs if not re.search(r"REFER[ÊE]NCIAS", p.text, re.I))
|
| 83 |
+
return max(1, palavras // 350)
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
def _set_run_font(run, nome, tamanho_pt, negrito=None, italico=None):
|
| 86 |
+
run.font.name = nome; run.font.size = Pt(tamanho_pt)
|
|
|
|
| 87 |
if negrito is not None: run.font.bold = negrito
|
| 88 |
if italico is not None: run.font.italic = italico
|
| 89 |
|
| 90 |
def substituir_texto_cross_run(para, original, corrigido) -> int:
|
|
|
|
| 91 |
if original not in para.text: return 0
|
|
|
|
|
|
|
| 92 |
for run in para.runs:
|
| 93 |
if original in run.text:
|
| 94 |
run.text = run.text.replace(original, corrigido, 1)
|
| 95 |
return 1
|
| 96 |
+
# fragmentado
|
| 97 |
+
estilo = para.runs[0].font if para.runs else None
|
| 98 |
+
texto = para.text.replace(original, corrigido, 1)
|
|
|
|
| 99 |
para.clear()
|
| 100 |
+
novo = para.add_run(texto)
|
| 101 |
+
if estilo:
|
| 102 |
+
novo.font.name = estilo.name; novo.font.size = estilo.size
|
| 103 |
return 1
|
| 104 |
|
| 105 |
def formatacao_cruzada_indices(para, texto_alvo, aplicar_italico=False, aplicar_negrito=False) -> int:
|
| 106 |
+
aplic = 0
|
| 107 |
if aplicar_italico:
|
| 108 |
+
matches = list(re.finditer(r'\b' + re.escape(texto_alvo) + r'\b', para.text, re.I))
|
| 109 |
else:
|
| 110 |
idx = para.text.find(texto_alvo)
|
| 111 |
+
matches = [(idx, idx+len(texto_alvo))] if idx!= -1 else []
|
| 112 |
+
for m in matches:
|
| 113 |
+
ini, fim = m if isinstance(m, tuple) else (m.start(), m.end())
|
| 114 |
+
if ini == -1: continue
|
| 115 |
+
pos = 0
|
|
|
|
| 116 |
for run in para.runs:
|
| 117 |
+
fim_run = pos + len(run.text)
|
| 118 |
+
if pos < fim and fim_run > ini:
|
| 119 |
if aplicar_italico: run.italic = True
|
| 120 |
if aplicar_negrito: run.bold = True
|
| 121 |
+
aplic += 1
|
| 122 |
+
pos = fim_run
|
| 123 |
+
return aplic
|
| 124 |
|
| 125 |
def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
| 126 |
+
for sec in doc.sections:
|
| 127 |
+
sec.page_height, sec.page_width = Cm(29.7), Cm(21.0)
|
| 128 |
+
sec.top_margin, sec.left_margin = Cm(3.0), Cm(3.0)
|
| 129 |
+
sec.bottom_margin, sec.right_margin = Cm(2.0), Cm(2.0)
|
| 130 |
+
sec.header_distance, sec.footer_distance = Cm(0.5), Cm(0.5)
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
em_refs, em_resumo = False, False
|
| 133 |
for para in doc.paragraphs:
|
| 134 |
+
txt = para.text.strip()
|
| 135 |
+
if not txt: continue
|
| 136 |
+
pf = para.paragraph_format
|
| 137 |
+
style = (para.style.name or "").lower()
|
| 138 |
|
| 139 |
+
if re.match(r"^RESUMO\b", txt, re.I): em_resumo, em_refs = True, False
|
| 140 |
+
elif re.match(r"^(?:INTRODU[ÇC]|ABSTRACT|1[\s\.])", txt, re.I): em_resumo = False
|
| 141 |
|
| 142 |
+
is_ref = bool(re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS\b", txt, re.I))
|
| 143 |
+
if is_ref: em_refs = True
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
if em_refs and not is_ref:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
pf.alignment, pf.first_line_indent, pf.left_indent = WD_ALIGN_PARAGRAPH.LEFT, Cm(0), Cm(0)
|
| 147 |
pf.space_before, pf.space_after, pf.line_spacing = Pt(0), Pt(6), 1.0
|
| 148 |
+
for r in para.runs: _set_run_font(r, "Calibri", 11)
|
| 149 |
+
elif is_ref:
|
| 150 |
+
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER; pf.space_before = Pt(12); pf.space_after = Pt(12); pf.line_spacing = 1.5
|
| 151 |
+
for r in para.runs: _set_run_font(r, "Calibri", 12, negrito=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
elif em_resumo:
|
| 153 |
+
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY; pf.first_line_indent = Cm(0); pf.line_spacing = 1.5
|
| 154 |
+
for r in para.runs:
|
| 155 |
+
is_label = bool(re.match(r"^(RESUMO|PALAVRAS|ABSTRACT|KEYWORDS)", r.text.strip(), re.I))
|
| 156 |
+
_set_run_font(r, "Calibri", 11, negrito=is_label)
|
| 157 |
+
elif "heading" in style or (txt.isupper() and 3 < len(txt) < 120):
|
| 158 |
+
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER; pf.line_spacing = 1.5
|
| 159 |
+
for r in para.runs: _set_run_font(r, "Calibri", 14, negrito=True)
|
| 160 |
+
elif pf.left_indent and pf.left_indent >= Cm(3.5): # citação longa
|
| 161 |
+
pf.left_indent = Cm(4.0); pf.first_line_indent = Cm(0); pf.line_spacing = 1.0
|
| 162 |
+
for r in para.runs: _set_run_font(r, "Calibri", 11)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
else:
|
| 164 |
+
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY; pf.first_line_indent = Cm(1.25); pf.line_spacing = 1.5
|
| 165 |
+
for r in para.runs: _set_run_font(r, "Calibri", 12)
|
|
|
|
| 166 |
|
| 167 |
+
# ─── 5. INTERFACE ──────────────────────────────────────
|
| 168 |
+
st.title("⚖ Assistente Acadêmico - Direito UNIFAGOC")
|
| 169 |
+
aba_auditoria, aba_revisao, aba_abnt, aba_prompt, aba_feedback = st.tabs([
|
| 170 |
+
"🔍 Auditoria", "🧠 Revisão", "📐 ABNT", "🤖 Prompt Mestre", "👨🏫 Feedback"
|
|
|
|
|
|
|
| 171 |
])
|
| 172 |
|
| 173 |
+
# ABA 1: AUDITORIA
|
|
|
|
|
|
|
| 174 |
with aba_auditoria:
|
| 175 |
+
st.markdown("Cruze Pré-Projeto com TCC e gere nota da banca (80 pontos).")
|
| 176 |
+
fase = st.radio("Fase:", ["TCC 1 (Intro + Cap1)", "TCC 2 (Completo)"], horizontal=True, on_change=reset_estado, args=("resultado_auditoria",))
|
| 177 |
+
c1, c2 = st.columns(2)
|
| 178 |
+
with c1: arq_proj = st.file_uploader("1. Pré-Projeto", type="docx", key="proj", on_change=reset_estado, args=("resultado_auditoria",))
|
| 179 |
+
with c2: arq_tcc = st.file_uploader("2. TCC", type="docx", key="tcc_aud", on_change=reset_estado, args=("resultado_auditoria",))
|
| 180 |
+
|
| 181 |
+
if st.button("🔍 Iniciar Auditoria", type="primary"):
|
| 182 |
+
if arq_proj and arq_tcc:
|
| 183 |
+
with st.status("Analisando...", expanded=True) as s:
|
| 184 |
+
txt_proj = extrair_texto_docx(arq_proj)
|
| 185 |
+
txt_tcc = extrair_texto_docx(arq_tcc)
|
| 186 |
+
regra = "TCC 1: não penalize ausência de conclusão." if "TCC 1" in fase else "TCC 2: exija trabalho completo."
|
| 187 |
+
prompt = f"Como Professor UNIFAGOC: {regra}\nPRÉ-PROJETO:\n{txt_proj}\n\nTCC:\n{txt_tcc}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
try:
|
| 189 |
+
res = client.models.generate_content(model=MODEL, contents=prompt,
|
| 190 |
+
config=types.GenerateContentConfig(temperature=0.0, response_mime_type="application/json", response_schema=AuditoriaTCC))
|
|
|
|
|
|
|
| 191 |
st.session_state.resultado_auditoria = json.loads(res.text)
|
| 192 |
+
s.update(label="Concluído", state="complete")
|
| 193 |
+
except Exception as e: st.error(e)
|
| 194 |
+
else: st.warning("Envie os dois arquivos.")
|
|
|
|
| 195 |
|
| 196 |
if st.session_state.resultado_auditoria:
|
| 197 |
+
d = st.session_state.resultado_auditoria
|
| 198 |
+
total = sum([d.get("nota_tema_problema",0), d.get("nota_introducao_metodo",0), d.get("nota_estruturacao",0), d.get("nota_formatacao_abnt",0)])
|
| 199 |
+
c1,c2,c3,c4 = st.columns(4)
|
| 200 |
+
c1.metric("Tema", f"{d['nota_tema_problema']}/20"); c2.metric("Intro", f"{d['nota_introducao_metodo']}/20")
|
| 201 |
+
c3.metric("Estrutura", f"{d['nota_estruturacao']}/20"); c4.metric("ABNT", f"{d['nota_formatacao_abnt']}/20")
|
| 202 |
+
st.info(f"**NOTA FINAL: {total}/80** - {d['justificativa_notas_banca']}")
|
| 203 |
+
st.metric("Aderência", f"{d['aderencia_percentual']}%")
|
| 204 |
+
|
| 205 |
+
# ABA 2: REVISÃO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
with aba_revisao:
|
| 207 |
+
st.markdown("Corrige ortografia, CAIXA ALTA e aplica itálico.")
|
| 208 |
+
arq_rev = st.file_uploader("TCC", type="docx", key="rev", on_change=reset_estado, args=("doc_revisado_bytes",))
|
| 209 |
+
if st.button("🧠 Revisar"):
|
|
|
|
| 210 |
if arq_rev:
|
| 211 |
+
with st.spinner("Revisando..."):
|
|
|
|
| 212 |
texto = extrair_texto_docx(arq_rev)
|
| 213 |
+
prompt = f"Localize erros ortográficos e termos latinos para itálico.\nTEXTO:\n{texto[:50000]}"
|
| 214 |
+
res = client.models.generate_content(model=MODEL, contents=prompt,
|
| 215 |
+
config=types.GenerateContentConfig(temperature=0.1, response_mime_type="application/json", response_schema=RevisaoInteligente))
|
| 216 |
+
dados = json.loads(res.text)
|
| 217 |
+
doc = Document(arq_rev)
|
| 218 |
+
for c in dados.get("correcoes", []):
|
| 219 |
+
for p in doc.paragraphs: substituir_texto_cross_run(p, c["original"], c["corrigido"])
|
| 220 |
+
for t in dados.get("termos_estrangeiros_para_italico", []):
|
| 221 |
+
for p in doc.paragraphs: formatacao_cruzada_indices(p, t, aplicar_italico=True)
|
| 222 |
+
st.session_state.doc_revisado_bytes = docx_to_bytes(doc)
|
| 223 |
+
st.session_state.nome_arq_rev = f"{arq_rev.name.replace('.docx','')}_Revisado.docx"
|
| 224 |
+
st.success("Revisão concluída")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
if st.session_state.doc_revisado_bytes:
|
| 226 |
+
st.download_button("⬇ Baixar Revisado", st.session_state.doc_revisado_bytes, st.session_state.nome_arq_rev)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
+
# ABA 3: ABNT
|
|
|
|
|
|
|
| 229 |
with aba_abnt:
|
| 230 |
+
st.markdown("Formatação fiel UNIFAGOC.")
|
| 231 |
+
arq_abnt = st.file_uploader("TCC", type="docx", key="abnt", on_change=reset_estado, args=("doc_formatado_bytes",))
|
| 232 |
+
if st.button("📐 Formatar"):
|
|
|
|
| 233 |
if arq_abnt:
|
| 234 |
+
doc = Document(arq_abnt)
|
| 235 |
+
pag = estimar_paginas(doc)
|
| 236 |
+
if pag > 18: st.warning(f"🚨 {pag} páginas - limite é 18")
|
| 237 |
+
aplicar_formatacao_unifagoc_abnt(doc)
|
| 238 |
+
# análise de referências
|
| 239 |
+
refs = [(i,p.text) for i,p in enumerate(doc.paragraphs) if len(p.text)>20 and re.search(r"\d{4}", p.text)]
|
| 240 |
+
if refs:
|
| 241 |
+
txt_refs = "\n".join(f"[{i}] {t}" for i,t in refs[:30])
|
| 242 |
+
prompt = f"Analise ABNT NBR 6023 e retorne elemento para negrito.\n{txt_refs}"
|
| 243 |
+
try:
|
| 244 |
+
res = client.models.generate_content(model=MODEL, contents=prompt,
|
| 245 |
+
config=types.GenerateContentConfig(temperature=0, response_mime_type="application/json", response_schema=AnaliseABNT))
|
| 246 |
+
dados = json.loads(res.text)
|
| 247 |
+
for prob in dados.get("problemas", []):
|
| 248 |
+
if prob["numero"] < len(doc.paragraphs):
|
| 249 |
+
formatacao_cruzada_indices(doc.paragraphs[prob["numero"]], prob["elemento_negrito"], aplicar_negrito=True)
|
| 250 |
+
except: pass
|
| 251 |
+
st.session_state.doc_formatado_bytes = docx_to_bytes(doc)
|
| 252 |
+
st.session_state.nome_arq_abnt = f"{arq_abnt.name.replace('.docx','')}_Formatado.docx"
|
| 253 |
+
st.success("Formatado")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
if st.session_state.doc_formatado_bytes:
|
| 255 |
+
st.download_button("⬇ Baixar Formatado", st.session_state.doc_formatado_bytes, st.session_state.nome_arq_abnt)
|
| 256 |
+
|
| 257 |
+
# ABA 4: PROMPT
|
| 258 |
+
with aba_prompt:
|
| 259 |
+
st.markdown("### 🤖 Prompt Mestre UNIFAGOC")
|
| 260 |
+
prompt_mestre = """Você é o Professor Examinador titular da banca de Direito da UNIFAGOC.
|
| 261 |
+
1. Compare PRÉ-PROJETO com TCC e calcule aderência
|
| 262 |
+
2. Identifique fuga de tema e 'linguiça'
|
| 263 |
+
3. Avalie citações: leis começam com BRASIL
|
| 264 |
+
4. Dê notas 0-80 (Tema 20, Intro 20, Estrutura 20, ABNT 20)
|
| 265 |
+
Responda em JSON."""
|
| 266 |
+
st.code(prompt_mestre); st.download_button("⬇ Baixar", prompt_mestre, "prompt_unifagoc.txt")
|
| 267 |
+
|
| 268 |
+
# ABA 5: FEEDBACK
|
| 269 |
+
with aba_feedback:
|
| 270 |
+
st.markdown("### 👨🏫 Feedback do Professor")
|
| 271 |
+
arq_fb = st.file_uploader("TCC", type="docx", key="fb")
|
| 272 |
+
if st.button("📊 Gerar Feedback", type="primary"):
|
| 273 |
+
if arq_fb:
|
| 274 |
+
texto = extrair_texto_docx(arq_fb)
|
| 275 |
+
prompt = f"Analise fluidez, parágrafos curtos, citações apud e formatação UNIFAGOC.\n{texto[:20000]}"
|
| 276 |
+
res = client.models.generate_content(model=MODEL, contents=prompt, config=types.GenerateContentConfig(temperature=0.3))
|
| 277 |
+
st.markdown(res.text)
|
| 278 |
+
|
| 279 |
+
# SIDEBAR EXPORT
|
| 280 |
+
st.sidebar.header("Exportar Pacote")
|
| 281 |
+
if st.session_state.doc_revisado_bytes or st.session_state.doc_formatado_bytes:
|
| 282 |
+
if st.sidebar.button("📦 Gerar ZIP"):
|
| 283 |
+
mem = io.BytesIO()
|
| 284 |
+
with zipfile.ZipFile(mem, "w") as z:
|
| 285 |
+
if st.session_state.doc_revisado_bytes: z.writestr(st.session_state.nome_arq_rev, st.session_state.doc_revisado_bytes)
|
| 286 |
+
if st.session_state.doc_formatado_bytes: z.writestr(st.session_state.nome_arq_abnt, st.session_state.doc_formatado_bytes)
|
| 287 |
+
if st.session_state.resultado_auditoria: z.writestr("auditoria.json", json.dumps(st.session_state.resultado_auditoria, ensure_ascii=False, indent=2))
|
| 288 |
+
st.sidebar.download_button("⬇ Baixar ZIP", mem.getvalue(), "TCC_UNIFAGOC.zip", "application/zip")
|