Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,8 +4,9 @@ import re
|
|
| 4 |
import json
|
| 5 |
import streamlit as st
|
| 6 |
from docx import Document
|
| 7 |
-
from docx.shared import Cm, Pt
|
| 8 |
-
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
|
|
| 9 |
from docx.oxml.ns import qn
|
| 10 |
from docx.oxml import OxmlElement
|
| 11 |
from pydantic import BaseModel
|
|
@@ -14,9 +15,20 @@ from google import genai
|
|
| 14 |
from google.genai import types
|
| 15 |
|
| 16 |
# =====================================================
|
| 17 |
-
# CONFIGURAÇÕES GLOBAIS
|
| 18 |
# =====================================================
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
LATINISMOS = [
|
| 21 |
"habeas corpus", "data venia", "jus puniendi", "jus postulandi",
|
| 22 |
"mens legis", "ratio decidendi", "obiter dictum", "in casu",
|
|
@@ -76,7 +88,11 @@ class ListaReferencias(BaseModel):
|
|
| 76 |
# =====================================================
|
| 77 |
class RevisorIA:
|
| 78 |
def __init__(self):
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def auditar_tcc(self, texto_projeto: str, texto_tcc: str, fase_tcc: str) -> Optional[AuditoriaTCC]:
|
| 82 |
regra_fase = (
|
|
@@ -93,7 +109,7 @@ class RevisorIA:
|
|
| 93 |
)
|
| 94 |
try:
|
| 95 |
res = self.client.models.generate_content(
|
| 96 |
-
model="gemini-
|
| 97 |
contents=prompt,
|
| 98 |
config=types.GenerateContentConfig(
|
| 99 |
temperature=0.0,
|
|
@@ -114,7 +130,7 @@ class RevisorIA:
|
|
| 114 |
)
|
| 115 |
try:
|
| 116 |
res = self.client.models.generate_content(
|
| 117 |
-
model="gemini-
|
| 118 |
contents=prompt,
|
| 119 |
config=types.GenerateContentConfig(
|
| 120 |
temperature=0.1,
|
|
@@ -138,7 +154,7 @@ class RevisorIA:
|
|
| 138 |
)
|
| 139 |
try:
|
| 140 |
res = self.client.models.generate_content(
|
| 141 |
-
model="gemini-
|
| 142 |
contents=prompt,
|
| 143 |
config=types.GenerateContentConfig(
|
| 144 |
temperature=0.0,
|
|
@@ -193,7 +209,6 @@ class FormatadorUNIFAGOC:
|
|
| 193 |
fldChar.set(qn('w:fldCharType'), 'end')
|
| 194 |
run._r.append(fldChar)
|
| 195 |
|
| 196 |
-
# Formatação
|
| 197 |
for run in para.runs:
|
| 198 |
run.font.name = 'Calibri'
|
| 199 |
run.font.size = Pt(10)
|
|
@@ -209,6 +224,7 @@ class FormatadorUNIFAGOC:
|
|
| 209 |
run.font.name = 'Calibri'
|
| 210 |
run.font.size = Pt(12)
|
| 211 |
run.bold = True
|
|
|
|
| 212 |
# Formata legenda
|
| 213 |
idx = doc.paragraphs.index(para)
|
| 214 |
if idx + 1 < len(doc.paragraphs):
|
|
@@ -217,7 +233,7 @@ class FormatadorUNIFAGOC:
|
|
| 217 |
run.font.name = 'Calibri'
|
| 218 |
run.font.size = Pt(11)
|
| 219 |
|
| 220 |
-
# Formata tabelas
|
| 221 |
for table in doc.tables:
|
| 222 |
for row in table.rows:
|
| 223 |
for cell in row.cells:
|
|
@@ -230,14 +246,14 @@ class FormatadorUNIFAGOC:
|
|
| 230 |
|
| 231 |
@staticmethod
|
| 232 |
def formatar_imagens(doc: Document):
|
| 233 |
-
"""Centraliza imagens (inline shapes)
|
| 234 |
for para in doc.paragraphs:
|
| 235 |
if para._p.xpath('.//w:drawing') or para._p.xpath('.//w:pic'):
|
| 236 |
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 237 |
|
| 238 |
@staticmethod
|
| 239 |
def formatar_notas_rodape(doc: Document):
|
| 240 |
-
"""Formata notas de rodapé (¹, ², ³)"""
|
| 241 |
for para in doc.paragraphs:
|
| 242 |
if re.search(r'[\d\^]+$', para.text.strip()):
|
| 243 |
for run in para.runs:
|
|
@@ -247,50 +263,57 @@ class FormatadorUNIFAGOC:
|
|
| 247 |
@staticmethod
|
| 248 |
def substituir_texto_preservando_formato(para, original: str, corrigido: str) -> int:
|
| 249 |
"""
|
| 250 |
-
Substitui texto PRESERVANDO formatação
|
| 251 |
-
|
| 252 |
"""
|
| 253 |
texto_completo = "".join(run.text for run in para.runs)
|
| 254 |
if original not in texto_completo:
|
| 255 |
return 0
|
| 256 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
pos = texto_completo.find(original)
|
| 258 |
if pos == -1:
|
| 259 |
return 0
|
| 260 |
|
| 261 |
-
# Divide o texto em partes: antes, original, depois
|
| 262 |
antes = texto_completo[:pos]
|
| 263 |
depois = texto_completo[pos + len(original):]
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
| 267 |
if antes:
|
| 268 |
para.add_run(antes)
|
| 269 |
-
|
| 270 |
-
# 2. Adiciona a parte corrigida (com formatação padrão)
|
| 271 |
run_corrigido = para.add_run(corrigido)
|
| 272 |
run_corrigido.font.name = 'Calibri'
|
| 273 |
run_corrigido.font.size = Pt(12)
|
| 274 |
|
| 275 |
-
# 3. Adiciona a parte "depois" com a formatação original
|
| 276 |
if depois:
|
| 277 |
para.add_run(depois)
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
return 1
|
| 280 |
|
| 281 |
@staticmethod
|
| 282 |
-
def formatar_documento(doc: Document) -> List[ProblemaReferencia]:
|
| 283 |
-
"""Função principal de formatação
|
| 284 |
-
# 1. Aplica margens e paginação
|
| 285 |
FormatadorUNIFAGOC.aplicar_margens(doc)
|
| 286 |
FormatadorUNIFAGOC.adicionar_paginacao(doc)
|
| 287 |
-
|
| 288 |
-
# 2. Formata elementos específicos
|
| 289 |
FormatadorUNIFAGOC.formatar_figuras_tabelas(doc)
|
| 290 |
FormatadorUNIFAGOC.formatar_imagens(doc)
|
| 291 |
FormatadorUNIFAGOC.formatar_notas_rodape(doc)
|
| 292 |
|
| 293 |
-
# 3. Processa cada parágrafo com fluxo único
|
| 294 |
for para in doc.paragraphs:
|
| 295 |
texto = para.text.strip()
|
| 296 |
if not texto:
|
|
@@ -371,7 +394,7 @@ class FormatadorUNIFAGOC:
|
|
| 371 |
run.font.size = Pt(12)
|
| 372 |
continue
|
| 373 |
|
| 374 |
-
# --- CORPO DO TEXTO ---
|
| 375 |
para.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 376 |
para.paragraph_format.first_line_indent = Cm(1.25)
|
| 377 |
para.paragraph_format.line_spacing = 1.5
|
|
@@ -381,34 +404,55 @@ class FormatadorUNIFAGOC:
|
|
| 381 |
run.font.name = 'Calibri'
|
| 382 |
run.font.size = Pt(12)
|
| 383 |
|
| 384 |
-
# 4. Valida referências
|
| 385 |
refs = FormatadorUNIFAGOC.extrair_referencias(doc)
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
@staticmethod
|
| 391 |
def detectar_nivel_secao(texto: str) -> int:
|
| 392 |
match = re.match(r'^(\d+(?:\.\d+)*)\s+', texto)
|
| 393 |
-
if not match:
|
| 394 |
-
return 0
|
| 395 |
return match.group(1).count('.') + 1
|
| 396 |
|
| 397 |
@staticmethod
|
| 398 |
def detectar_titulo_ou_subtitulo(texto: str) -> Optional[str]:
|
| 399 |
SECOES_ESPECIAIS = ["INTRODUÇÃO", "CONSIDERAÇÕES FINAIS", "REFERÊNCIAS", "RESUMO", "PALAVRAS-CHAVE"]
|
| 400 |
texto_upper = texto.upper()
|
| 401 |
-
if any(sec in texto_upper for sec in SECOES_ESPECIAIS):
|
| 402 |
-
|
| 403 |
-
if FormatadorUNIFAGOC.detectar_nivel_secao(texto)
|
| 404 |
-
return "titulo"
|
| 405 |
-
if texto.isupper() and len(texto) < 150 and not FormatadorUNIFAGOC.detectar_nivel_secao(texto):
|
| 406 |
-
return "titulo"
|
| 407 |
return None
|
| 408 |
|
| 409 |
@staticmethod
|
| 410 |
def detectar_citacao_longa(para) -> bool:
|
| 411 |
-
"""Detecção robusta: 40+ palavras OU recuo >= 3.5cm"""
|
| 412 |
if para.paragraph_format.left_indent and para.paragraph_format.left_indent >= Cm(3.5):
|
| 413 |
return True
|
| 414 |
texto = para.text.strip()
|
|
@@ -418,12 +462,10 @@ class FormatadorUNIFAGOC:
|
|
| 418 |
|
| 419 |
@staticmethod
|
| 420 |
def detectar_lista(texto: str) -> bool:
|
| 421 |
-
"""Regex preciso para listas (evita falsos positivos)"""
|
| 422 |
return bool(re.match(r'^(\d+[\)\.]|[a-zA-Z][\)\.]|[IVXLCDM]+[\)\.]|[-–])\s', texto))
|
| 423 |
|
| 424 |
@staticmethod
|
| 425 |
def extrair_referencias(doc: Document) -> List[str]:
|
| 426 |
-
"""Extrai todas as referências do documento"""
|
| 427 |
refs = []
|
| 428 |
em_refs = False
|
| 429 |
for para in doc.paragraphs:
|
|
@@ -457,11 +499,11 @@ class FormatadorUNIFAGOC:
|
|
| 457 |
return max(1, palavras_totais // 350)
|
| 458 |
|
| 459 |
# =====================================================
|
| 460 |
-
# CLASSE AUDITOR TCC (Responsável
|
| 461 |
# =====================================================
|
| 462 |
class AuditorTCC:
|
| 463 |
-
def __init__(self):
|
| 464 |
-
self.revisor =
|
| 465 |
|
| 466 |
def auditar(self, arq_projeto, arq_tcc, fase_tcc: str) -> Optional[AuditoriaTCC]:
|
| 467 |
texto_projeto = FormatadorUNIFAGOC.extrair_texto_docx(arq_projeto)
|
|
@@ -469,12 +511,11 @@ class AuditorTCC:
|
|
| 469 |
return self.revisor.auditar_tcc(texto_projeto, texto_tcc, fase_tcc)
|
| 470 |
|
| 471 |
def revisar(self, arq_rev) -> Tuple[Document, RevisaoInteligente, List[str]]:
|
| 472 |
-
"""Revisa documento com chunking para grandes arquivos"""
|
| 473 |
doc = Document(arq_rev)
|
| 474 |
texto_completo = FormatadorUNIFAGOC.extrair_texto_docx(arq_rev)
|
| 475 |
erros_locais = self.verificar_erros_locais(texto_completo)
|
| 476 |
|
| 477 |
-
# Chunking
|
| 478 |
chunks = self.dividir_em_chunks(texto_completo)
|
| 479 |
resultados_revisao = []
|
| 480 |
|
|
@@ -483,53 +524,50 @@ class AuditorTCC:
|
|
| 483 |
if resultado:
|
| 484 |
resultados_revisao.append(resultado)
|
| 485 |
|
| 486 |
-
# Consolida resultados
|
| 487 |
revisao_consolidada = self.consolidar_revisoes(resultados_revisao)
|
| 488 |
-
|
| 489 |
-
# Aplica correções no documento
|
| 490 |
self.aplicar_correcoes(doc, revisao_consolidada)
|
| 491 |
|
| 492 |
return doc, revisao_consolidada, erros_locais
|
| 493 |
|
| 494 |
def verificar_erros_locais(self, texto: str) -> List[str]:
|
| 495 |
erros = []
|
| 496 |
-
if re.search(r"\s{2,}", texto):
|
| 497 |
-
|
| 498 |
-
if re.search(r",
|
| 499 |
-
|
| 500 |
-
if re.search(r"[
|
| 501 |
-
erros.append("Pontuação repetida indevida (ex: '!!' ou '..').")
|
| 502 |
-
if re.search(r"\b(\w+)\s+\1\b", texto, re.IGNORECASE):
|
| 503 |
-
erros.append("Palavras repetidas sequencialmente (ex: 'o o', 'de de').")
|
| 504 |
-
if re.search(r"\([A-ZÀ-Ú\s]+,\s*\)", texto):
|
| 505 |
-
erros.append("Citação ABNT com ano faltando (ex: (SILVA, )).")
|
| 506 |
return erros
|
| 507 |
|
| 508 |
def dividir_em_chunks(self, texto: str) -> List[str]:
|
| 509 |
-
"""Divide texto em chunks de
|
|
|
|
| 510 |
chunks = []
|
| 511 |
-
|
| 512 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
return chunks
|
| 514 |
|
| 515 |
def consolidar_revisoes(self, revisoes: List[RevisaoInteligente]) -> RevisaoInteligente:
|
| 516 |
-
"""Consolida múltiplas revisões em uma única"""
|
| 517 |
if not revisoes:
|
| 518 |
return RevisaoInteligente(correcoes=[], problemas_academicos=[], termos_estrangeiros_para_italico=[])
|
| 519 |
-
|
| 520 |
-
# Consolida correções
|
| 521 |
todas_correcoes = []
|
| 522 |
-
for revisao in revisoes:
|
| 523 |
-
todas_correcoes.extend(revisao.correcoes)
|
| 524 |
-
|
| 525 |
-
# Consolida problemas acadêmicos
|
| 526 |
todos_problemas = []
|
| 527 |
-
for revisao in revisoes:
|
| 528 |
-
todos_problemas.extend(revisao.problemas_academicos)
|
| 529 |
-
|
| 530 |
-
# Consolida termos estrangeiros
|
| 531 |
todos_termos = []
|
|
|
|
| 532 |
for revisao in revisoes:
|
|
|
|
|
|
|
| 533 |
todos_termos.extend(revisao.termos_estrangeiros_para_italico)
|
| 534 |
|
| 535 |
return RevisaoInteligente(
|
|
@@ -539,31 +577,22 @@ class AuditorTCC:
|
|
| 539 |
)
|
| 540 |
|
| 541 |
def aplicar_correcoes(self, doc: Document, revisao: RevisaoInteligente):
|
| 542 |
-
"""Aplica correções no documento (incluindo tabelas)"""
|
| 543 |
-
# Aplica correções em parágrafos
|
| 544 |
for para in doc.paragraphs:
|
| 545 |
for correcao in revisao.correcoes:
|
| 546 |
-
FormatadorUNIFAGOC.substituir_texto_preservando_formato(
|
| 547 |
-
para, correcao.original, correcao.corrigido
|
| 548 |
-
)
|
| 549 |
|
| 550 |
-
# Aplica correções em tabelas
|
| 551 |
for table in doc.tables:
|
| 552 |
for row in table.rows:
|
| 553 |
for cell in row.cells:
|
| 554 |
for para in cell.paragraphs:
|
| 555 |
for correcao in revisao.correcoes:
|
| 556 |
-
FormatadorUNIFAGOC.substituir_texto_preservando_formato(
|
| 557 |
-
para, correcao.original, correcao.corrigido
|
| 558 |
-
)
|
| 559 |
|
| 560 |
-
# Aplica itálico em termos estrangeiros
|
| 561 |
termos_para_italico = set(LATINISMOS + revisao.termos_estrangeiros_para_italico)
|
| 562 |
for para in doc.paragraphs:
|
| 563 |
for termo in termos_para_italico:
|
| 564 |
FormatadorUNIFAGOC.formatacao_cruzada_indices(para, termo, aplicar_italico=True)
|
| 565 |
|
| 566 |
-
# Formata tabelas
|
| 567 |
for table in doc.tables:
|
| 568 |
for row in table.rows:
|
| 569 |
for cell in row.cells:
|
|
@@ -571,31 +600,6 @@ class AuditorTCC:
|
|
| 571 |
for termo in termos_para_italico:
|
| 572 |
FormatadorUNIFAGOC.formatacao_cruzada_indices(para, termo, aplicar_italico=True)
|
| 573 |
|
| 574 |
-
@staticmethod
|
| 575 |
-
def formatacao_cruzada_indices(para, texto_alvo: str, aplicar_italico: bool = False, aplicar_negrito: bool = False) -> int:
|
| 576 |
-
aplicacoes = 0
|
| 577 |
-
if aplicar_italico:
|
| 578 |
-
matches = list(re.finditer(r'\b' + re.escape(texto_alvo) + r'\b', para.text, re.IGNORECASE))
|
| 579 |
-
else:
|
| 580 |
-
idx = para.text.find(texto_alvo)
|
| 581 |
-
matches = [(idx, idx + len(texto_alvo))] if idx != -1 else []
|
| 582 |
-
|
| 583 |
-
for match in matches:
|
| 584 |
-
pos_ini, pos_fim = match if isinstance(match, tuple) else (match.start(), match.end())
|
| 585 |
-
if pos_ini == -1:
|
| 586 |
-
continue
|
| 587 |
-
pos_atual = 0
|
| 588 |
-
for run in para.runs:
|
| 589 |
-
fim_run = pos_atual + len(run.text)
|
| 590 |
-
if pos_atual < pos_fim and fim_run > pos_ini:
|
| 591 |
-
if aplicar_italico:
|
| 592 |
-
run.italic = True
|
| 593 |
-
if aplicar_negrito:
|
| 594 |
-
run.bold = True
|
| 595 |
-
aplicacoes += 1
|
| 596 |
-
pos_atual += len(run.text)
|
| 597 |
-
return aplicacoes
|
| 598 |
-
|
| 599 |
# =====================================================
|
| 600 |
# INTERFACE STREAMLIT
|
| 601 |
# =====================================================
|
|
@@ -608,8 +612,9 @@ aba_auditoria, aba_revisao, aba_abnt, aba_prompt, aba_feedback = st.tabs([
|
|
| 608 |
"👨🏫 Feedback Professor"
|
| 609 |
])
|
| 610 |
|
| 611 |
-
# Inicialização das classes
|
| 612 |
-
|
|
|
|
| 613 |
formatador = FormatadorUNIFAGOC()
|
| 614 |
|
| 615 |
# ABA 1: AUDITORIA
|
|
@@ -697,9 +702,8 @@ with aba_abnt:
|
|
| 697 |
if paginas_estimadas > 18:
|
| 698 |
st.warning(f"🚨 Extensão: {paginas_estimadas} páginas (limite: 18).")
|
| 699 |
|
| 700 |
-
refs_com_erros = formatador.formatar_documento(doc_abnt)
|
| 701 |
|
| 702 |
-
# Exibe erros de referências na interface
|
| 703 |
if refs_com_erros:
|
| 704 |
st.subheader("⚠️ Erros em Referências ABNT")
|
| 705 |
for ref in refs_com_erros:
|
|
@@ -747,8 +751,8 @@ with aba_feedback:
|
|
| 747 |
f"Texto: {texto}"
|
| 748 |
)
|
| 749 |
try:
|
| 750 |
-
res =
|
| 751 |
-
model="gemini-
|
| 752 |
contents=prompt_fb,
|
| 753 |
config=types.GenerateContentConfig(temperature=0.2)
|
| 754 |
)
|
|
|
|
| 4 |
import json
|
| 5 |
import streamlit as st
|
| 6 |
from docx import Document
|
| 7 |
+
from docx.shared import Cm, Pt, RGBColor
|
| 8 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK
|
| 9 |
+
from docx.enum.section import WD_SECTION
|
| 10 |
from docx.oxml.ns import qn
|
| 11 |
from docx.oxml import OxmlElement
|
| 12 |
from pydantic import BaseModel
|
|
|
|
| 15 |
from google.genai import types
|
| 16 |
|
| 17 |
# =====================================================
|
| 18 |
+
# CONFIGURAÇÕES GLOBAIS E ESTADO
|
| 19 |
# =====================================================
|
| 20 |
+
st.set_page_config(page_title="Corretor TCC - UNIFAGOC", page_icon="⚖️", layout="wide")
|
| 21 |
+
|
| 22 |
+
def reset_estado(chave):
|
| 23 |
+
if chave in st.session_state:
|
| 24 |
+
st.session_state[chave] = None
|
| 25 |
+
|
| 26 |
+
# Inicialização do estado
|
| 27 |
+
for key in ["resultado_auditoria", "doc_revisado_bytes", "doc_formatado_bytes"]:
|
| 28 |
+
if key not in st.session_state:
|
| 29 |
+
st.session_state[key] = None
|
| 30 |
+
|
| 31 |
+
MAX_CHARS_PER_CHUNK = 15000 # Limite de segurança para a janela de contexto
|
| 32 |
LATINISMOS = [
|
| 33 |
"habeas corpus", "data venia", "jus puniendi", "jus postulandi",
|
| 34 |
"mens legis", "ratio decidendi", "obiter dictum", "in casu",
|
|
|
|
| 88 |
# =====================================================
|
| 89 |
class RevisorIA:
|
| 90 |
def __init__(self):
|
| 91 |
+
api_key = st.secrets.get("GEMINI_API_KEY") or os.environ.get("GEMINI_API_KEY")
|
| 92 |
+
if not api_key:
|
| 93 |
+
st.error("❌ ERRO: Chave GEMINI_API_KEY não configurada nos secrets.")
|
| 94 |
+
st.stop()
|
| 95 |
+
self.client = genai.Client(api_key=api_key)
|
| 96 |
|
| 97 |
def auditar_tcc(self, texto_projeto: str, texto_tcc: str, fase_tcc: str) -> Optional[AuditoriaTCC]:
|
| 98 |
regra_fase = (
|
|
|
|
| 109 |
)
|
| 110 |
try:
|
| 111 |
res = self.client.models.generate_content(
|
| 112 |
+
model="gemini-1.5-flash",
|
| 113 |
contents=prompt,
|
| 114 |
config=types.GenerateContentConfig(
|
| 115 |
temperature=0.0,
|
|
|
|
| 130 |
)
|
| 131 |
try:
|
| 132 |
res = self.client.models.generate_content(
|
| 133 |
+
model="gemini-1.5-flash",
|
| 134 |
contents=prompt,
|
| 135 |
config=types.GenerateContentConfig(
|
| 136 |
temperature=0.1,
|
|
|
|
| 154 |
)
|
| 155 |
try:
|
| 156 |
res = self.client.models.generate_content(
|
| 157 |
+
model="gemini-1.5-flash",
|
| 158 |
contents=prompt,
|
| 159 |
config=types.GenerateContentConfig(
|
| 160 |
temperature=0.0,
|
|
|
|
| 209 |
fldChar.set(qn('w:fldCharType'), 'end')
|
| 210 |
run._r.append(fldChar)
|
| 211 |
|
|
|
|
| 212 |
for run in para.runs:
|
| 213 |
run.font.name = 'Calibri'
|
| 214 |
run.font.size = Pt(10)
|
|
|
|
| 224 |
run.font.name = 'Calibri'
|
| 225 |
run.font.size = Pt(12)
|
| 226 |
run.bold = True
|
| 227 |
+
|
| 228 |
# Formata legenda
|
| 229 |
idx = doc.paragraphs.index(para)
|
| 230 |
if idx + 1 < len(doc.paragraphs):
|
|
|
|
| 233 |
run.font.name = 'Calibri'
|
| 234 |
run.font.size = Pt(11)
|
| 235 |
|
| 236 |
+
# Formata tabelas internas
|
| 237 |
for table in doc.tables:
|
| 238 |
for row in table.rows:
|
| 239 |
for cell in row.cells:
|
|
|
|
| 246 |
|
| 247 |
@staticmethod
|
| 248 |
def formatar_imagens(doc: Document):
|
| 249 |
+
"""Centraliza imagens (inline shapes)"""
|
| 250 |
for para in doc.paragraphs:
|
| 251 |
if para._p.xpath('.//w:drawing') or para._p.xpath('.//w:pic'):
|
| 252 |
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 253 |
|
| 254 |
@staticmethod
|
| 255 |
def formatar_notas_rodape(doc: Document):
|
| 256 |
+
"""Formata notas de rodapé (¹, ², ³) representadas no texto principal"""
|
| 257 |
for para in doc.paragraphs:
|
| 258 |
if re.search(r'[\d\^]+$', para.text.strip()):
|
| 259 |
for run in para.runs:
|
|
|
|
| 263 |
@staticmethod
|
| 264 |
def substituir_texto_preservando_formato(para, original: str, corrigido: str) -> int:
|
| 265 |
"""
|
| 266 |
+
Substitui texto PRESERVANDO formatação.
|
| 267 |
+
Tenta substituir dentro do próprio run primeiro para preservar hiperlinks e estilos mistos.
|
| 268 |
"""
|
| 269 |
texto_completo = "".join(run.text for run in para.runs)
|
| 270 |
if original not in texto_completo:
|
| 271 |
return 0
|
| 272 |
|
| 273 |
+
# Tentativa 1: Substituição cirúrgica no mesmo run (preserva 100% da formatação)
|
| 274 |
+
for run in para.runs:
|
| 275 |
+
if original in run.text:
|
| 276 |
+
run.text = run.text.replace(original, corrigido, 1)
|
| 277 |
+
return 1
|
| 278 |
+
|
| 279 |
+
# Tentativa 2: Fallback caso a palavra esteja quebrada entre runs diferentes
|
| 280 |
pos = texto_completo.find(original)
|
| 281 |
if pos == -1:
|
| 282 |
return 0
|
| 283 |
|
|
|
|
| 284 |
antes = texto_completo[:pos]
|
| 285 |
depois = texto_completo[pos + len(original):]
|
| 286 |
|
| 287 |
+
estilo_base = para.style
|
| 288 |
+
alinhamento = para.paragraph_format.alignment
|
| 289 |
+
|
| 290 |
+
para.clear()
|
| 291 |
if antes:
|
| 292 |
para.add_run(antes)
|
| 293 |
+
|
|
|
|
| 294 |
run_corrigido = para.add_run(corrigido)
|
| 295 |
run_corrigido.font.name = 'Calibri'
|
| 296 |
run_corrigido.font.size = Pt(12)
|
| 297 |
|
|
|
|
| 298 |
if depois:
|
| 299 |
para.add_run(depois)
|
| 300 |
|
| 301 |
+
if estilo_base:
|
| 302 |
+
para.style = estilo_base
|
| 303 |
+
if alinhamento:
|
| 304 |
+
para.paragraph_format.alignment = alinhamento
|
| 305 |
+
|
| 306 |
return 1
|
| 307 |
|
| 308 |
@staticmethod
|
| 309 |
+
def formatar_documento(doc: Document, revisor: RevisorIA) -> List[ProblemaReferencia]:
|
| 310 |
+
"""Função principal de formatação estrutural (ABNT UNIFAGOC)"""
|
|
|
|
| 311 |
FormatadorUNIFAGOC.aplicar_margens(doc)
|
| 312 |
FormatadorUNIFAGOC.adicionar_paginacao(doc)
|
|
|
|
|
|
|
| 313 |
FormatadorUNIFAGOC.formatar_figuras_tabelas(doc)
|
| 314 |
FormatadorUNIFAGOC.formatar_imagens(doc)
|
| 315 |
FormatadorUNIFAGOC.formatar_notas_rodape(doc)
|
| 316 |
|
|
|
|
| 317 |
for para in doc.paragraphs:
|
| 318 |
texto = para.text.strip()
|
| 319 |
if not texto:
|
|
|
|
| 394 |
run.font.size = Pt(12)
|
| 395 |
continue
|
| 396 |
|
| 397 |
+
# --- CORPO DO TEXTO PADRÃO ---
|
| 398 |
para.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 399 |
para.paragraph_format.first_line_indent = Cm(1.25)
|
| 400 |
para.paragraph_format.line_spacing = 1.5
|
|
|
|
| 404 |
run.font.name = 'Calibri'
|
| 405 |
run.font.size = Pt(12)
|
| 406 |
|
| 407 |
+
# 4. Valida referências extraídas no documento
|
| 408 |
refs = FormatadorUNIFAGOC.extrair_referencias(doc)
|
| 409 |
+
if refs:
|
| 410 |
+
lista_refs = revisor.validar_referencias(refs)
|
| 411 |
+
return lista_refs.referencias
|
| 412 |
+
return []
|
| 413 |
+
|
| 414 |
+
@staticmethod
|
| 415 |
+
def formatacao_cruzada_indices(para, texto_alvo: str, aplicar_italico: bool = False, aplicar_negrito: bool = False) -> int:
|
| 416 |
+
aplicacoes = 0
|
| 417 |
+
if aplicar_italico:
|
| 418 |
+
matches = list(re.finditer(r'\b' + re.escape(texto_alvo) + r'\b', para.text, re.IGNORECASE))
|
| 419 |
+
else:
|
| 420 |
+
idx = para.text.find(texto_alvo)
|
| 421 |
+
matches = [(idx, idx + len(texto_alvo))] if idx != -1 else []
|
| 422 |
+
|
| 423 |
+
for match in matches:
|
| 424 |
+
pos_ini, pos_fim = match if isinstance(match, tuple) else (match.start(), match.end())
|
| 425 |
+
if pos_ini == -1:
|
| 426 |
+
continue
|
| 427 |
+
pos_atual = 0
|
| 428 |
+
for run in para.runs:
|
| 429 |
+
fim_run = pos_atual + len(run.text)
|
| 430 |
+
if pos_atual < pos_fim and fim_run > pos_ini:
|
| 431 |
+
if aplicar_italico:
|
| 432 |
+
run.italic = True
|
| 433 |
+
if aplicar_negrito:
|
| 434 |
+
run.bold = True
|
| 435 |
+
aplicacoes += 1
|
| 436 |
+
pos_atual += len(run.text)
|
| 437 |
+
return aplicacoes
|
| 438 |
|
| 439 |
@staticmethod
|
| 440 |
def detectar_nivel_secao(texto: str) -> int:
|
| 441 |
match = re.match(r'^(\d+(?:\.\d+)*)\s+', texto)
|
| 442 |
+
if not match: return 0
|
|
|
|
| 443 |
return match.group(1).count('.') + 1
|
| 444 |
|
| 445 |
@staticmethod
|
| 446 |
def detectar_titulo_ou_subtitulo(texto: str) -> Optional[str]:
|
| 447 |
SECOES_ESPECIAIS = ["INTRODUÇÃO", "CONSIDERAÇÕES FINAIS", "REFERÊNCIAS", "RESUMO", "PALAVRAS-CHAVE"]
|
| 448 |
texto_upper = texto.upper()
|
| 449 |
+
if any(sec in texto_upper for sec in SECOES_ESPECIAIS): return "titulo"
|
| 450 |
+
if FormatadorUNIFAGOC.detectar_nivel_secao(texto) > 0: return "titulo"
|
| 451 |
+
if texto.isupper() and len(texto) < 150 and not FormatadorUNIFAGOC.detectar_nivel_secao(texto): return "titulo"
|
|
|
|
|
|
|
|
|
|
| 452 |
return None
|
| 453 |
|
| 454 |
@staticmethod
|
| 455 |
def detectar_citacao_longa(para) -> bool:
|
|
|
|
| 456 |
if para.paragraph_format.left_indent and para.paragraph_format.left_indent >= Cm(3.5):
|
| 457 |
return True
|
| 458 |
texto = para.text.strip()
|
|
|
|
| 462 |
|
| 463 |
@staticmethod
|
| 464 |
def detectar_lista(texto: str) -> bool:
|
|
|
|
| 465 |
return bool(re.match(r'^(\d+[\)\.]|[a-zA-Z][\)\.]|[IVXLCDM]+[\)\.]|[-–])\s', texto))
|
| 466 |
|
| 467 |
@staticmethod
|
| 468 |
def extrair_referencias(doc: Document) -> List[str]:
|
|
|
|
| 469 |
refs = []
|
| 470 |
em_refs = False
|
| 471 |
for para in doc.paragraphs:
|
|
|
|
| 499 |
return max(1, palavras_totais // 350)
|
| 500 |
|
| 501 |
# =====================================================
|
| 502 |
+
# CLASSE AUDITOR TCC (Responsável pela lógica da aplicação)
|
| 503 |
# =====================================================
|
| 504 |
class AuditorTCC:
|
| 505 |
+
def __init__(self, revisor: RevisorIA):
|
| 506 |
+
self.revisor = revisor
|
| 507 |
|
| 508 |
def auditar(self, arq_projeto, arq_tcc, fase_tcc: str) -> Optional[AuditoriaTCC]:
|
| 509 |
texto_projeto = FormatadorUNIFAGOC.extrair_texto_docx(arq_projeto)
|
|
|
|
| 511 |
return self.revisor.auditar_tcc(texto_projeto, texto_tcc, fase_tcc)
|
| 512 |
|
| 513 |
def revisar(self, arq_rev) -> Tuple[Document, RevisaoInteligente, List[str]]:
|
|
|
|
| 514 |
doc = Document(arq_rev)
|
| 515 |
texto_completo = FormatadorUNIFAGOC.extrair_texto_docx(arq_rev)
|
| 516 |
erros_locais = self.verificar_erros_locais(texto_completo)
|
| 517 |
|
| 518 |
+
# Chunking seguro respeitando parágrafos
|
| 519 |
chunks = self.dividir_em_chunks(texto_completo)
|
| 520 |
resultados_revisao = []
|
| 521 |
|
|
|
|
| 524 |
if resultado:
|
| 525 |
resultados_revisao.append(resultado)
|
| 526 |
|
|
|
|
| 527 |
revisao_consolidada = self.consolidar_revisoes(resultados_revisao)
|
|
|
|
|
|
|
| 528 |
self.aplicar_correcoes(doc, revisao_consolidada)
|
| 529 |
|
| 530 |
return doc, revisao_consolidada, erros_locais
|
| 531 |
|
| 532 |
def verificar_erros_locais(self, texto: str) -> List[str]:
|
| 533 |
erros = []
|
| 534 |
+
if re.search(r"\s{2,}", texto): erros.append("Espaços duplos detectados no documento.")
|
| 535 |
+
if re.search(r",\s*,", texto): erros.append("Vírgulas duplicadas detectadas (ex: ',,').")
|
| 536 |
+
if re.search(r"[.!?]{2,}", texto) and not "..." in texto: erros.append("Pontuação repetida indevida.")
|
| 537 |
+
if re.search(r"\b(\w+)\s+\1\b", texto, re.IGNORECASE): erros.append("Palavras repetidas sequencialmente.")
|
| 538 |
+
if re.search(r"\([A-ZÀ-Ú\s]+,\s*\)", texto): erros.append("Citação ABNT com ano faltando.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
return erros
|
| 540 |
|
| 541 |
def dividir_em_chunks(self, texto: str) -> List[str]:
|
| 542 |
+
"""Divide texto em chunks respeitando a quebra de parágrafos"""
|
| 543 |
+
paragrafos = texto.split('\n\n')
|
| 544 |
chunks = []
|
| 545 |
+
chunk_atual = ""
|
| 546 |
+
|
| 547 |
+
for p in paragrafos:
|
| 548 |
+
if len(chunk_atual) + len(p) + 2 < MAX_CHARS_PER_CHUNK:
|
| 549 |
+
chunk_atual += p + "\n\n"
|
| 550 |
+
else:
|
| 551 |
+
if chunk_atual:
|
| 552 |
+
chunks.append(chunk_atual.strip())
|
| 553 |
+
chunk_atual = p + "\n\n"
|
| 554 |
+
|
| 555 |
+
if chunk_atual:
|
| 556 |
+
chunks.append(chunk_atual.strip())
|
| 557 |
+
|
| 558 |
return chunks
|
| 559 |
|
| 560 |
def consolidar_revisoes(self, revisoes: List[RevisaoInteligente]) -> RevisaoInteligente:
|
|
|
|
| 561 |
if not revisoes:
|
| 562 |
return RevisaoInteligente(correcoes=[], problemas_academicos=[], termos_estrangeiros_para_italico=[])
|
| 563 |
+
|
|
|
|
| 564 |
todas_correcoes = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
todos_problemas = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
todos_termos = []
|
| 567 |
+
|
| 568 |
for revisao in revisoes:
|
| 569 |
+
todas_correcoes.extend(revisao.correcoes)
|
| 570 |
+
todos_problemas.extend(revisao.problemas_academicos)
|
| 571 |
todos_termos.extend(revisao.termos_estrangeiros_para_italico)
|
| 572 |
|
| 573 |
return RevisaoInteligente(
|
|
|
|
| 577 |
)
|
| 578 |
|
| 579 |
def aplicar_correcoes(self, doc: Document, revisao: RevisaoInteligente):
|
|
|
|
|
|
|
| 580 |
for para in doc.paragraphs:
|
| 581 |
for correcao in revisao.correcoes:
|
| 582 |
+
FormatadorUNIFAGOC.substituir_texto_preservando_formato(para, correcao.original, correcao.corrigido)
|
|
|
|
|
|
|
| 583 |
|
|
|
|
| 584 |
for table in doc.tables:
|
| 585 |
for row in table.rows:
|
| 586 |
for cell in row.cells:
|
| 587 |
for para in cell.paragraphs:
|
| 588 |
for correcao in revisao.correcoes:
|
| 589 |
+
FormatadorUNIFAGOC.substituir_texto_preservando_formato(para, correcao.original, correcao.corrigido)
|
|
|
|
|
|
|
| 590 |
|
|
|
|
| 591 |
termos_para_italico = set(LATINISMOS + revisao.termos_estrangeiros_para_italico)
|
| 592 |
for para in doc.paragraphs:
|
| 593 |
for termo in termos_para_italico:
|
| 594 |
FormatadorUNIFAGOC.formatacao_cruzada_indices(para, termo, aplicar_italico=True)
|
| 595 |
|
|
|
|
| 596 |
for table in doc.tables:
|
| 597 |
for row in table.rows:
|
| 598 |
for cell in row.cells:
|
|
|
|
| 600 |
for termo in termos_para_italico:
|
| 601 |
FormatadorUNIFAGOC.formatacao_cruzada_indices(para, termo, aplicar_italico=True)
|
| 602 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 603 |
# =====================================================
|
| 604 |
# INTERFACE STREAMLIT
|
| 605 |
# =====================================================
|
|
|
|
| 612 |
"👨🏫 Feedback Professor"
|
| 613 |
])
|
| 614 |
|
| 615 |
+
# Inicialização centralizada das classes
|
| 616 |
+
revisor_ia = RevisorIA()
|
| 617 |
+
auditor = AuditorTCC(revisor_ia)
|
| 618 |
formatador = FormatadorUNIFAGOC()
|
| 619 |
|
| 620 |
# ABA 1: AUDITORIA
|
|
|
|
| 702 |
if paginas_estimadas > 18:
|
| 703 |
st.warning(f"🚨 Extensão: {paginas_estimadas} páginas (limite: 18).")
|
| 704 |
|
| 705 |
+
refs_com_erros = formatador.formatar_documento(doc_abnt, revisor_ia)
|
| 706 |
|
|
|
|
| 707 |
if refs_com_erros:
|
| 708 |
st.subheader("⚠️ Erros em Referências ABNT")
|
| 709 |
for ref in refs_com_erros:
|
|
|
|
| 751 |
f"Texto: {texto}"
|
| 752 |
)
|
| 753 |
try:
|
| 754 |
+
res = revisor_ia.client.models.generate_content(
|
| 755 |
+
model="gemini-1.5-flash",
|
| 756 |
contents=prompt_fb,
|
| 757 |
config=types.GenerateContentConfig(temperature=0.2)
|
| 758 |
)
|