Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -21,6 +21,15 @@ if "resultado_auditoria" not in st.session_state: st.session_state.resultado_aud
|
|
| 21 |
if "doc_revisado_bytes" not in st.session_state: st.session_state.doc_revisado_bytes = None
|
| 22 |
if "doc_formatado_bytes" not in st.session_state: st.session_state.doc_formatado_bytes = None
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# ─── 2. ESQUEMAS DE DADOS ESTRITOS (PYDANTIC) ─────────────────────────────
|
| 25 |
class AuditoriaTCC(BaseModel):
|
| 26 |
aderencia_percentual: int
|
|
@@ -32,6 +41,7 @@ class AuditoriaTCC(BaseModel):
|
|
| 32 |
objetivos_nao_cumpridos_no_tcc: list[str]
|
| 33 |
desvios_de_tema_ou_linguica: list[str]
|
| 34 |
indicios_texto_generico_ia: list[str]
|
|
|
|
| 35 |
nota_tema_problema: float
|
| 36 |
nota_introducao_metodo: float
|
| 37 |
nota_estruturacao: float
|
|
@@ -42,9 +52,19 @@ class ErroTexto(BaseModel):
|
|
| 42 |
original: str
|
| 43 |
corrigido: str
|
| 44 |
motivo: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
class RevisaoInteligente(BaseModel):
|
| 47 |
correcoes: list[ErroTexto]
|
|
|
|
| 48 |
termos_estrangeiros_para_italico: list[str]
|
| 49 |
|
| 50 |
class ProblemaReferencia(BaseModel):
|
|
@@ -84,16 +104,25 @@ def estimar_paginas(doc: Document) -> int:
|
|
| 84 |
return max(1, palavras_totais // 350)
|
| 85 |
|
| 86 |
def substituir_texto_cross_run(para, original, corrigido) -> int:
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
for run in para.runs:
|
| 89 |
if original in run.text:
|
| 90 |
run.text = run.text.replace(original, corrigido, 1)
|
| 91 |
return 1
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
| 94 |
para.clear()
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
return 1
|
| 98 |
|
| 99 |
def formatacao_cruzada_indices(para, texto_alvo, aplicar_italico=False, aplicar_negrito=False) -> int:
|
|
@@ -117,13 +146,25 @@ def formatacao_cruzada_indices(para, texto_alvo, aplicar_italico=False, aplicar_
|
|
| 117 |
pos_atual += len(run.text)
|
| 118 |
return aplicacoes
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
# ─── MOTOR ABNT CORRIGIDO COM BASE NO RELATÓRIO DO UTILIZADOR ─────────────
|
| 121 |
def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
| 122 |
-
"""
|
| 123 |
-
Novo Motor Baseado em Estados (State Machine) que respeita rigorosamente
|
| 124 |
-
os valores XML reais do template UNIFAGOC reportados no diagnóstico.
|
| 125 |
-
"""
|
| 126 |
-
# Geometria da Página
|
| 127 |
for section in doc.sections:
|
| 128 |
section.page_height = Cm(29.7)
|
| 129 |
section.page_width = Cm(21.0)
|
|
@@ -134,7 +175,7 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 134 |
section.header_distance = Cm(0.5)
|
| 135 |
section.footer_distance = Cm(0.5)
|
| 136 |
|
| 137 |
-
fase_atual = "PRE_RESUMO"
|
| 138 |
|
| 139 |
for i, para in enumerate(doc.paragraphs):
|
| 140 |
texto = para.text.strip()
|
|
@@ -143,7 +184,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 143 |
texto_upper = texto.upper()
|
| 144 |
pf = para.paragraph_format
|
| 145 |
|
| 146 |
-
# --- MÁQUINA DE ESTADOS (Identifica a secção do documento) ---
|
| 147 |
if texto_upper == "RESUMO":
|
| 148 |
fase_atual = "RESUMO_LBL"
|
| 149 |
elif fase_atual == "RESUMO_LBL":
|
|
@@ -160,11 +200,8 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 160 |
elif fase_atual == "REF_TITLE":
|
| 161 |
fase_atual = "REF_ENTRY"
|
| 162 |
|
| 163 |
-
# --- APLICAÇÃO CIRÚRGICA DE FORMATAÇÃO ---
|
| 164 |
-
|
| 165 |
if fase_atual == "PRE_RESUMO":
|
| 166 |
if i == 0 or (texto.isupper() and len(texto) < 150):
|
| 167 |
-
# TÍTULO PRINCIPAL: CENTER, 14pt, bold, 1.5x, sem recuo
|
| 168 |
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 169 |
pf.first_line_indent = None
|
| 170 |
pf.left_indent = None
|
|
@@ -176,20 +213,18 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 176 |
run.font.size = Pt(14)
|
| 177 |
run.font.bold = True
|
| 178 |
else:
|
| 179 |
-
# AUTORES: CENTER, 12pt, herda tamanho, sem recuo, reseta ls
|
| 180 |
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 181 |
pf.first_line_indent = None
|
| 182 |
pf.left_indent = None
|
| 183 |
pf.space_before = Pt(0)
|
| 184 |
pf.space_after = Pt(0)
|
| 185 |
-
pf.line_spacing = None
|
| 186 |
for run in para.runs:
|
| 187 |
run.font.name = 'Calibri'
|
| 188 |
run.font.size = Pt(12)
|
| 189 |
run.font.bold = False
|
| 190 |
|
| 191 |
elif fase_atual == "RESUMO_LBL":
|
| 192 |
-
# Título RESUMO: sp_before = 12pt
|
| 193 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 194 |
pf.first_line_indent = None
|
| 195 |
pf.left_indent = None
|
|
@@ -203,7 +238,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 203 |
run.font.italic = False
|
| 204 |
|
| 205 |
elif fase_atual == "RESUMO_BODY":
|
| 206 |
-
# Corpo do Resumo: Calibri 11pt itálico
|
| 207 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 208 |
pf.first_line_indent = None
|
| 209 |
pf.left_indent = None
|
|
@@ -217,7 +251,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 217 |
run.font.bold = False
|
| 218 |
|
| 219 |
elif fase_atual == "PALAVRAS_CH":
|
| 220 |
-
# Palavras-chave: sp_before = 6pt
|
| 221 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 222 |
pf.first_line_indent = None
|
| 223 |
pf.left_indent = None
|
|
@@ -236,7 +269,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 236 |
|
| 237 |
elif fase_atual == "CORPO":
|
| 238 |
if texto.isupper() and len(texto) < 120:
|
| 239 |
-
# HEADINGS H2 (Seções): JUSTIFY + sp_after = 12pt
|
| 240 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 241 |
pf.first_line_indent = None
|
| 242 |
pf.left_indent = None
|
|
@@ -248,7 +280,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 248 |
run.font.size = Pt(12)
|
| 249 |
run.font.bold = True
|
| 250 |
elif pf.left_indent is not None and pf.left_indent >= Cm(3.5):
|
| 251 |
-
# CITAÇÕES LONGAS: Calibri 11pt, recuo 4cm, espaçamento simples
|
| 252 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 253 |
pf.first_line_indent = None
|
| 254 |
pf.left_indent = Cm(4.0)
|
|
@@ -259,7 +290,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 259 |
run.font.name = 'Calibri'
|
| 260 |
run.font.size = Pt(11)
|
| 261 |
else:
|
| 262 |
-
# CORPO PADRÃO: 12pt explicito e indent 1.25 consistente
|
| 263 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 264 |
pf.first_line_indent = Cm(1.25)
|
| 265 |
pf.left_indent = None
|
|
@@ -271,7 +301,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 271 |
run.font.size = Pt(12)
|
| 272 |
|
| 273 |
elif fase_atual == "REF_TITLE":
|
| 274 |
-
# Heading "REFERÊNCIAS": CENTER + apenas ls=1.5 (sem sp)
|
| 275 |
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 276 |
pf.first_line_indent = None
|
| 277 |
pf.left_indent = None
|
|
@@ -284,7 +313,6 @@ def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
| 284 |
run.font.bold = True
|
| 285 |
|
| 286 |
elif fase_atual == "REF_ENTRY":
|
| 287 |
-
# Entradas de Referências: sp_before=6pt + sp_after=0pt
|
| 288 |
pf.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
| 289 |
pf.first_line_indent = None
|
| 290 |
pf.left_indent = None
|
|
@@ -309,7 +337,7 @@ aba_auditoria, aba_revisao, aba_abnt, aba_prompt, aba_feedback = st.tabs([
|
|
| 309 |
# ABA 1: AUDITORIA E PONTUAÇÃO UNIFAGOC
|
| 310 |
# ==============================================================================
|
| 311 |
with aba_auditoria:
|
| 312 |
-
st.markdown("Cruze o **Pré-Projeto** com o **TCC** para identificar fuga do tema e gerar a **Nota da Banca (80 pontos)**.")
|
| 313 |
fase_tcc = st.radio("Fase atual:", ["TCC 1 (Apenas Introdução e Capítulo 1)", "TCC 2 (TCC Completo)"], horizontal=True, on_change=reset_estado, args=("resultado_auditoria",))
|
| 314 |
|
| 315 |
col1, col2 = st.columns(2)
|
|
@@ -320,22 +348,22 @@ with aba_auditoria:
|
|
| 320 |
if not arq_projeto or not arq_tcc:
|
| 321 |
st.warning("⚠️ Envie os DOIS ficheiros para realizar a comparação.")
|
| 322 |
else:
|
| 323 |
-
with st.status("A analisar argumentação jurídica...", expanded=True) as status:
|
| 324 |
st.write("A extrair textos dos documentos...")
|
| 325 |
texto_projeto = extrair_texto_docx(arq_projeto)
|
| 326 |
texto_tcc = extrair_texto_docx(arq_tcc)
|
| 327 |
|
| 328 |
regra_fase = (
|
| 329 |
"ATENÇÃO: O aluno está em TCC 1. NÃO penalize a ausência de Resumo e Conclusão."
|
| 330 |
-
if "TCC 1" in fase_tcc
|
| 331 |
-
else "O aluno está em TCC 2. Exija o trabalho completo."
|
| 332 |
)
|
| 333 |
prompt = (
|
| 334 |
f"Como Professor Examinador titular da banca de Direito da UNIFAGOC:\n{regra_fase}\n"
|
| 335 |
f"=== PRÉ-PROJETO ===\n{texto_projeto}\n"
|
| 336 |
f"=== TCC ===\n{texto_tcc}\n"
|
| 337 |
"TAREFA 1: Avalie o cruzamento de dados, fuga de tema e objetivos.\n"
|
| 338 |
-
"TAREFA 2:
|
|
|
|
| 339 |
)
|
| 340 |
|
| 341 |
st.write("A submeter dados à IA do Google...")
|
|
@@ -359,10 +387,8 @@ with aba_auditoria:
|
|
| 359 |
dados = st.session_state.resultado_auditoria
|
| 360 |
st.header("🏆 Avaliação da Banca UNIFAGOC")
|
| 361 |
nota_total = sum([
|
| 362 |
-
dados.get("nota_tema_problema", 0),
|
| 363 |
-
dados.get("
|
| 364 |
-
dados.get("nota_estruturacao", 0),
|
| 365 |
-
dados.get("nota_formatacao_abnt", 0)
|
| 366 |
])
|
| 367 |
|
| 368 |
c1, c2, c3, c4 = st.columns(4)
|
|
@@ -371,27 +397,30 @@ with aba_auditoria:
|
|
| 371 |
c3.metric("Estrutura/Linguagem", f"{dados.get('nota_estruturacao')}/20")
|
| 372 |
c4.metric("Formatação/ABNT", f"{dados.get('nota_formatacao_abnt')}/20")
|
| 373 |
|
| 374 |
-
st.info(
|
| 375 |
-
f"**NOTA FINAL TEXTUAL: {nota_total}/80 pontos**\n"
|
| 376 |
-
f"*Parecer da Banca:* {dados.get('justificativa_notas_banca')}"
|
| 377 |
-
)
|
| 378 |
st.divider()
|
| 379 |
|
| 380 |
st.metric("Índice de Aderência ao Projeto", f"{dados.get('aderencia_percentual')}%")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
col_a, col_b = st.columns(2)
|
| 382 |
with col_a:
|
| 383 |
st.subheader("🎯 Problema de Pesquisa")
|
| 384 |
-
if dados.get("tcc_respondeu_ao_problema"):
|
| 385 |
st.success(f"✅ O TCC respondeu: {dados.get('justificativa_problema')}")
|
| 386 |
-
else:
|
| 387 |
st.error(f"❌ Não respondeu: {dados.get('justificativa_problema')}")
|
| 388 |
with col_b:
|
| 389 |
st.subheader("📋 Objetivos")
|
| 390 |
-
for f in dados.get("objetivos_nao_cumpridos_no_tcc", []):
|
| 391 |
st.error(f"Faltou: {f}")
|
| 392 |
-
if not dados.get("objetivos_nao_cumpridos_no_tcc"):
|
| 393 |
-
st.success("✅ Todos os objetivos
|
| 394 |
-
|
| 395 |
st.subheader("🚨 Filtro Anti-Embromação")
|
| 396 |
for fuga in dados.get("desvios_de_tema_ou_linguica", []):
|
| 397 |
st.warning(f"Fuga: {fuga}")
|
|
@@ -402,21 +431,41 @@ with aba_auditoria:
|
|
| 402 |
# ABA 2: REVISÃO TEXTUAL INTELIGENTE
|
| 403 |
# ==============================================================================
|
| 404 |
with aba_revisao:
|
| 405 |
-
st.markdown("
|
| 406 |
arq_rev = st.file_uploader("Envie o TCC (.docx)", type=["docx"], key="revisao", on_change=reset_estado, args=("doc_revisado_bytes",))
|
| 407 |
|
| 408 |
-
if st.button("🧠 Realizar Revisão"):
|
| 409 |
if arq_rev:
|
| 410 |
-
with st.status("A processar
|
| 411 |
-
st.write("A
|
| 412 |
texto = extrair_texto_docx(arq_rev)
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
f"
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
-
st.write("A aguardar correções da Inteligência Artificial...")
|
| 420 |
try:
|
| 421 |
res = client.models.generate_content(
|
| 422 |
model="gemini-3.5-flash",
|
|
@@ -429,7 +478,7 @@ with aba_revisao:
|
|
| 429 |
)
|
| 430 |
dados = json.loads(res.text)
|
| 431 |
|
| 432 |
-
st.write("A aplicar correções cirúrgicas no Word...")
|
| 433 |
doc_rev = Document(arq_rev)
|
| 434 |
aplicadas_texto, aplicadas_italico = 0, 0
|
| 435 |
|
|
@@ -438,15 +487,23 @@ with aba_revisao:
|
|
| 438 |
for para in doc_rev.paragraphs:
|
| 439 |
aplicadas_texto += substituir_texto_cross_run(para, c["original"], c["corrigido"])
|
| 440 |
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
|
|
|
|
|
|
| 445 |
|
| 446 |
st.session_state.doc_revisado_bytes = docx_to_bytes(doc_rev)
|
| 447 |
st.session_state.nome_arq_rev = f"{arq_rev.name.replace('.docx', '')}_Revisado.docx"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
status.update(
|
| 449 |
-
label=f"Processo finalizado
|
| 450 |
state="complete", expanded=False
|
| 451 |
)
|
| 452 |
except Exception as e:
|
|
@@ -607,4 +664,4 @@ with aba_feedback:
|
|
| 607 |
)
|
| 608 |
st.write(res.text)
|
| 609 |
except Exception as e:
|
| 610 |
-
st.error(f"Erro ao gerar feedback: {e}")
|
|
|
|
| 21 |
if "doc_revisado_bytes" not in st.session_state: st.session_state.doc_revisado_bytes = None
|
| 22 |
if "doc_formatado_bytes" not in st.session_state: st.session_state.doc_formatado_bytes = None
|
| 23 |
|
| 24 |
+
# Dicionário Fixo de Latinismos Jurídicos
|
| 25 |
+
LATINISMOS = [
|
| 26 |
+
"habeas corpus", "data venia", "jus puniendi", "jus postulandi",
|
| 27 |
+
"mens legis", "ratio decidendi", "obiter dictum", "in casu",
|
| 28 |
+
"periculum in mora", "fumus boni iuris", "a quo", "ad quem",
|
| 29 |
+
"ex tunc", "ex nunc", "erga omnes", "vacatio legis",
|
| 30 |
+
"mutatis mutandis", "strictu sensu", "lato sensu", "sine qua non"
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
# ─── 2. ESQUEMAS DE DADOS ESTRITOS (PYDANTIC) ─────────────────────────────
|
| 34 |
class AuditoriaTCC(BaseModel):
|
| 35 |
aderencia_percentual: int
|
|
|
|
| 41 |
objetivos_nao_cumpridos_no_tcc: list[str]
|
| 42 |
desvios_de_tema_ou_linguica: list[str]
|
| 43 |
indicios_texto_generico_ia: list[str]
|
| 44 |
+
incoerencias_internas: list[str]
|
| 45 |
nota_tema_problema: float
|
| 46 |
nota_introducao_metodo: float
|
| 47 |
nota_estruturacao: float
|
|
|
|
| 52 |
original: str
|
| 53 |
corrigido: str
|
| 54 |
motivo: str
|
| 55 |
+
categoria: str
|
| 56 |
+
gravidade: str
|
| 57 |
+
contexto: str
|
| 58 |
+
|
| 59 |
+
class ProblemaAcademico(BaseModel):
|
| 60 |
+
trecho: str
|
| 61 |
+
problema: str
|
| 62 |
+
sugestao: str
|
| 63 |
+
gravidade: str
|
| 64 |
|
| 65 |
class RevisaoInteligente(BaseModel):
|
| 66 |
correcoes: list[ErroTexto]
|
| 67 |
+
problemas_academicos: list[ProblemaAcademico]
|
| 68 |
termos_estrangeiros_para_italico: list[str]
|
| 69 |
|
| 70 |
class ProblemaReferencia(BaseModel):
|
|
|
|
| 104 |
return max(1, palavras_totais // 350)
|
| 105 |
|
| 106 |
def substituir_texto_cross_run(para, original, corrigido) -> int:
|
| 107 |
+
texto_completo = "".join(run.text for run in para.runs)
|
| 108 |
+
if original not in texto_completo:
|
| 109 |
+
return 0
|
| 110 |
+
|
| 111 |
for run in para.runs:
|
| 112 |
if original in run.text:
|
| 113 |
run.text = run.text.replace(original, corrigido, 1)
|
| 114 |
return 1
|
| 115 |
+
|
| 116 |
+
novo_texto = texto_completo.replace(original, corrigido, 1)
|
| 117 |
+
estilo_base = para.style
|
| 118 |
+
alinhamento_base = para.paragraph_format.alignment
|
| 119 |
+
|
| 120 |
para.clear()
|
| 121 |
+
para.add_run(novo_texto)
|
| 122 |
+
para.style = estilo_base
|
| 123 |
+
if alinhamento_base:
|
| 124 |
+
para.paragraph_format.alignment = alinhamento_base
|
| 125 |
+
|
| 126 |
return 1
|
| 127 |
|
| 128 |
def formatacao_cruzada_indices(para, texto_alvo, aplicar_italico=False, aplicar_negrito=False) -> int:
|
|
|
|
| 146 |
pos_atual += len(run.text)
|
| 147 |
return aplicacoes
|
| 148 |
|
| 149 |
+
# ─── MOTOR DE VERIFICAÇÕES LOCAIS (REGEX) ─────────────────────────────────
|
| 150 |
+
def verificacoes_locais_regex(texto: str) -> list[str]:
|
| 151 |
+
erros = []
|
| 152 |
+
if re.search(r"\s{2,}", texto):
|
| 153 |
+
erros.append("Espaços duplos detectados no documento.")
|
| 154 |
+
if re.search(r",\s*,", texto):
|
| 155 |
+
erros.append("Vírgulas duplicadas detectadas (ex: ',,').")
|
| 156 |
+
if re.search(r"[.!?]{2,}", texto) and not "..." in texto:
|
| 157 |
+
erros.append("Pontuação repetida indevida (ex: '!!' ou '..').")
|
| 158 |
+
if re.search(r"\b(\w+)\s+\1\b", texto, re.IGNORECASE):
|
| 159 |
+
erros.append("Palavras repetidas sequencialmente (ex: 'o o', 'de de').")
|
| 160 |
+
|
| 161 |
+
if re.search(r"\([A-ZÀ-Ú\s]+,\s*\)", texto):
|
| 162 |
+
erros.append("Citação ABNT com ano faltando (ex: (SILVA, )).")
|
| 163 |
+
|
| 164 |
+
return erros
|
| 165 |
+
|
| 166 |
# ─── MOTOR ABNT CORRIGIDO COM BASE NO RELATÓRIO DO UTILIZADOR ─────────────
|
| 167 |
def aplicar_formatacao_unifagoc_abnt(doc: Document):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
for section in doc.sections:
|
| 169 |
section.page_height = Cm(29.7)
|
| 170 |
section.page_width = Cm(21.0)
|
|
|
|
| 175 |
section.header_distance = Cm(0.5)
|
| 176 |
section.footer_distance = Cm(0.5)
|
| 177 |
|
| 178 |
+
fase_atual = "PRE_RESUMO"
|
| 179 |
|
| 180 |
for i, para in enumerate(doc.paragraphs):
|
| 181 |
texto = para.text.strip()
|
|
|
|
| 184 |
texto_upper = texto.upper()
|
| 185 |
pf = para.paragraph_format
|
| 186 |
|
|
|
|
| 187 |
if texto_upper == "RESUMO":
|
| 188 |
fase_atual = "RESUMO_LBL"
|
| 189 |
elif fase_atual == "RESUMO_LBL":
|
|
|
|
| 200 |
elif fase_atual == "REF_TITLE":
|
| 201 |
fase_atual = "REF_ENTRY"
|
| 202 |
|
|
|
|
|
|
|
| 203 |
if fase_atual == "PRE_RESUMO":
|
| 204 |
if i == 0 or (texto.isupper() and len(texto) < 150):
|
|
|
|
| 205 |
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 206 |
pf.first_line_indent = None
|
| 207 |
pf.left_indent = None
|
|
|
|
| 213 |
run.font.size = Pt(14)
|
| 214 |
run.font.bold = True
|
| 215 |
else:
|
|
|
|
| 216 |
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 217 |
pf.first_line_indent = None
|
| 218 |
pf.left_indent = None
|
| 219 |
pf.space_before = Pt(0)
|
| 220 |
pf.space_after = Pt(0)
|
| 221 |
+
pf.line_spacing = None
|
| 222 |
for run in para.runs:
|
| 223 |
run.font.name = 'Calibri'
|
| 224 |
run.font.size = Pt(12)
|
| 225 |
run.font.bold = False
|
| 226 |
|
| 227 |
elif fase_atual == "RESUMO_LBL":
|
|
|
|
| 228 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 229 |
pf.first_line_indent = None
|
| 230 |
pf.left_indent = None
|
|
|
|
| 238 |
run.font.italic = False
|
| 239 |
|
| 240 |
elif fase_atual == "RESUMO_BODY":
|
|
|
|
| 241 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 242 |
pf.first_line_indent = None
|
| 243 |
pf.left_indent = None
|
|
|
|
| 251 |
run.font.bold = False
|
| 252 |
|
| 253 |
elif fase_atual == "PALAVRAS_CH":
|
|
|
|
| 254 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 255 |
pf.first_line_indent = None
|
| 256 |
pf.left_indent = None
|
|
|
|
| 269 |
|
| 270 |
elif fase_atual == "CORPO":
|
| 271 |
if texto.isupper() and len(texto) < 120:
|
|
|
|
| 272 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 273 |
pf.first_line_indent = None
|
| 274 |
pf.left_indent = None
|
|
|
|
| 280 |
run.font.size = Pt(12)
|
| 281 |
run.font.bold = True
|
| 282 |
elif pf.left_indent is not None and pf.left_indent >= Cm(3.5):
|
|
|
|
| 283 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 284 |
pf.first_line_indent = None
|
| 285 |
pf.left_indent = Cm(4.0)
|
|
|
|
| 290 |
run.font.name = 'Calibri'
|
| 291 |
run.font.size = Pt(11)
|
| 292 |
else:
|
|
|
|
| 293 |
pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
| 294 |
pf.first_line_indent = Cm(1.25)
|
| 295 |
pf.left_indent = None
|
|
|
|
| 301 |
run.font.size = Pt(12)
|
| 302 |
|
| 303 |
elif fase_atual == "REF_TITLE":
|
|
|
|
| 304 |
pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 305 |
pf.first_line_indent = None
|
| 306 |
pf.left_indent = None
|
|
|
|
| 313 |
run.font.bold = True
|
| 314 |
|
| 315 |
elif fase_atual == "REF_ENTRY":
|
|
|
|
| 316 |
pf.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
| 317 |
pf.first_line_indent = None
|
| 318 |
pf.left_indent = None
|
|
|
|
| 337 |
# ABA 1: AUDITORIA E PONTUAÇÃO UNIFAGOC
|
| 338 |
# ==============================================================================
|
| 339 |
with aba_auditoria:
|
| 340 |
+
st.markdown("Cruze o **Pré-Projeto** com o **TCC** para identificar fuga do tema, coerência e gerar a **Nota da Banca (80 pontos)**.")
|
| 341 |
fase_tcc = st.radio("Fase atual:", ["TCC 1 (Apenas Introdução e Capítulo 1)", "TCC 2 (TCC Completo)"], horizontal=True, on_change=reset_estado, args=("resultado_auditoria",))
|
| 342 |
|
| 343 |
col1, col2 = st.columns(2)
|
|
|
|
| 348 |
if not arq_projeto or not arq_tcc:
|
| 349 |
st.warning("⚠️ Envie os DOIS ficheiros para realizar a comparação.")
|
| 350 |
else:
|
| 351 |
+
with st.status("A analisar argumentação e coerência jurídica...", expanded=True) as status:
|
| 352 |
st.write("A extrair textos dos documentos...")
|
| 353 |
texto_projeto = extrair_texto_docx(arq_projeto)
|
| 354 |
texto_tcc = extrair_texto_docx(arq_tcc)
|
| 355 |
|
| 356 |
regra_fase = (
|
| 357 |
"ATENÇÃO: O aluno está em TCC 1. NÃO penalize a ausência de Resumo e Conclusão."
|
| 358 |
+
if "TCC 1" in fase_tcc else "O aluno está em TCC 2. Exija o trabalho completo."
|
|
|
|
| 359 |
)
|
| 360 |
prompt = (
|
| 361 |
f"Como Professor Examinador titular da banca de Direito da UNIFAGOC:\n{regra_fase}\n"
|
| 362 |
f"=== PRÉ-PROJETO ===\n{texto_projeto}\n"
|
| 363 |
f"=== TCC ===\n{texto_tcc}\n"
|
| 364 |
"TAREFA 1: Avalie o cruzamento de dados, fuga de tema e objetivos.\n"
|
| 365 |
+
"TAREFA 2: Verifique incoerências internas severas (ex: Introdução foca em um tema, mas capítulos focam em outro).\n"
|
| 366 |
+
"TAREFA 3: Distribua 80 pontos rigorosamente de acordo com os critérios da ficha UNIFAGOC."
|
| 367 |
)
|
| 368 |
|
| 369 |
st.write("A submeter dados à IA do Google...")
|
|
|
|
| 387 |
dados = st.session_state.resultado_auditoria
|
| 388 |
st.header("🏆 Avaliação da Banca UNIFAGOC")
|
| 389 |
nota_total = sum([
|
| 390 |
+
dados.get("nota_tema_problema", 0), dados.get("nota_introducao_metodo", 0),
|
| 391 |
+
dados.get("nota_estruturacao", 0), dados.get("nota_formatacao_abnt", 0)
|
|
|
|
|
|
|
| 392 |
])
|
| 393 |
|
| 394 |
c1, c2, c3, c4 = st.columns(4)
|
|
|
|
| 397 |
c3.metric("Estrutura/Linguagem", f"{dados.get('nota_estruturacao')}/20")
|
| 398 |
c4.metric("Formatação/ABNT", f"{dados.get('nota_formatacao_abnt')}/20")
|
| 399 |
|
| 400 |
+
st.info(f"**NOTA FINAL TEXTUAL: {nota_total}/80 pontos**\n\n*Parecer da Banca:* {dados.get('justificativa_notas_banca')}")
|
|
|
|
|
|
|
|
|
|
| 401 |
st.divider()
|
| 402 |
|
| 403 |
st.metric("Índice de Aderência ao Projeto", f"{dados.get('aderencia_percentual')}%")
|
| 404 |
+
|
| 405 |
+
if dados.get("incoerencias_internas"):
|
| 406 |
+
st.error("🚨 Incoerências Internas Detectadas:")
|
| 407 |
+
for inc in dados.get("incoerencias_internas"):
|
| 408 |
+
st.write(f"- {inc}")
|
| 409 |
+
|
| 410 |
col_a, col_b = st.columns(2)
|
| 411 |
with col_a:
|
| 412 |
st.subheader("🎯 Problema de Pesquisa")
|
| 413 |
+
if dados.get("tcc_respondeu_ao_problema"):
|
| 414 |
st.success(f"✅ O TCC respondeu: {dados.get('justificativa_problema')}")
|
| 415 |
+
else:
|
| 416 |
st.error(f"❌ Não respondeu: {dados.get('justificativa_problema')}")
|
| 417 |
with col_b:
|
| 418 |
st.subheader("📋 Objetivos")
|
| 419 |
+
for f in dados.get("objetivos_nao_cumpridos_no_tcc", []):
|
| 420 |
st.error(f"Faltou: {f}")
|
| 421 |
+
if not dados.get("objetivos_nao_cumpridos_no_tcc"):
|
| 422 |
+
st.success("✅ Todos os objetivos abordados.")
|
| 423 |
+
|
| 424 |
st.subheader("🚨 Filtro Anti-Embromação")
|
| 425 |
for fuga in dados.get("desvios_de_tema_ou_linguica", []):
|
| 426 |
st.warning(f"Fuga: {fuga}")
|
|
|
|
| 431 |
# ABA 2: REVISÃO TEXTUAL INTELIGENTE
|
| 432 |
# ==============================================================================
|
| 433 |
with aba_revisao:
|
| 434 |
+
st.markdown("Revisão de múltiplas camadas: **Ortografia**, **Gramática**, **Coerência**, **Vícios Jurídicos** e motor anti-IA.")
|
| 435 |
arq_rev = st.file_uploader("Envie o TCC (.docx)", type=["docx"], key="revisao", on_change=reset_estado, args=("doc_revisado_bytes",))
|
| 436 |
|
| 437 |
+
if st.button("🧠 Realizar Revisão Acadêmica"):
|
| 438 |
if arq_rev:
|
| 439 |
+
with st.status("A processar Revisão em Múltiplas Camadas...", expanded=True) as status:
|
| 440 |
+
st.write("1. A executar verificações locais (Regex)...")
|
| 441 |
texto = extrair_texto_docx(arq_rev)
|
| 442 |
+
|
| 443 |
+
erros_locais = verificacoes_locais_regex(texto)
|
| 444 |
+
for erro in erros_locais:
|
| 445 |
+
st.warning(f"⚠️ Verificação Rápida: {erro}")
|
| 446 |
+
|
| 447 |
+
st.write("2. A submeter texto à Revisão Mestre do Google Gemini...")
|
| 448 |
+
|
| 449 |
+
prompt_rev = f"""
|
| 450 |
+
Você é um Professor e Revisor Rigoroso de TCCs de Direito da UNIFAGOC.
|
| 451 |
+
Analise o texto linha por linha.
|
| 452 |
+
|
| 453 |
+
Localize e corrija:
|
| 454 |
+
1. ORTOGRAFIA E GRAMÁTICA: Concordância verbal e nominal, regência, crase, pontuação.
|
| 455 |
+
2. VÍCIOS DE ESCRITA JURÍDICA: Repetição excessiva de palavras, períodos excessivamente longos (mais de 4 linhas sem ponto final), uso excessivo de voz passiva, parágrafos de uma frase só, repetição da expressão "Diante do exposto", linguagem coloquial.
|
| 456 |
+
3. TEXTO "CARA DE IA": Identifique generalizações sem fonte ("A tecnologia vem transformando..."), conclusões óbvias, repetição de estrutura sintática.
|
| 457 |
+
4. COESÃO E COERÊNCIA: Furos no argumento ou parágrafos desconexos.
|
| 458 |
+
5. ABNT E RIGOR ACADÊMICO: Identifique afirmações sem fundamento legal, jurisprudência jogada sem fonte, excesso de "apud".
|
| 459 |
+
6. FORMATAÇÃO: Caixa alta inadequada no corpo do texto.
|
| 460 |
+
|
| 461 |
+
NÃO IGNORE NENHUM ERRO. Retorne TODOS os erros encontrados.
|
| 462 |
+
|
| 463 |
+
No objeto de retorno 'termos_estrangeiros_para_italico', não inclua os termos básicos se não houverem.
|
| 464 |
+
|
| 465 |
+
Texto para revisar:
|
| 466 |
+
{texto}
|
| 467 |
+
"""
|
| 468 |
|
|
|
|
| 469 |
try:
|
| 470 |
res = client.models.generate_content(
|
| 471 |
model="gemini-3.5-flash",
|
|
|
|
| 478 |
)
|
| 479 |
dados = json.loads(res.text)
|
| 480 |
|
| 481 |
+
st.write("3. A aplicar correções cirúrgicas no Word (Cross-Run ativado)...")
|
| 482 |
doc_rev = Document(arq_rev)
|
| 483 |
aplicadas_texto, aplicadas_italico = 0, 0
|
| 484 |
|
|
|
|
| 487 |
for para in doc_rev.paragraphs:
|
| 488 |
aplicadas_texto += substituir_texto_cross_run(para, c["original"], c["corrigido"])
|
| 489 |
|
| 490 |
+
st.write("4. A aplicar Itálico Automático em Latinismos e Termos Estrangeiros...")
|
| 491 |
+
termos_para_italico = set(LATINISMOS + dados.get("termos_estrangeiros_para_italico", []))
|
| 492 |
+
|
| 493 |
+
for termo in termos_para_italico:
|
| 494 |
+
for para in doc_rev.paragraphs:
|
| 495 |
+
aplicadas_italico += formatacao_cruzada_indices(para, termo, aplicar_italico=True)
|
| 496 |
|
| 497 |
st.session_state.doc_revisado_bytes = docx_to_bytes(doc_rev)
|
| 498 |
st.session_state.nome_arq_rev = f"{arq_rev.name.replace('.docx', '')}_Revisado.docx"
|
| 499 |
+
|
| 500 |
+
if dados.get("problemas_academicos"):
|
| 501 |
+
st.subheader("🚨 Problemas de Redação e Rigor Acadêmico Detectados")
|
| 502 |
+
for prob in dados["problemas_academicos"]:
|
| 503 |
+
st.error(f"**[{prob['gravidade'].upper()}] {prob['problema']}**\n\nTrecho: '{prob['trecho']}'\n\nSugestão: {prob['sugestao']}")
|
| 504 |
+
|
| 505 |
status.update(
|
| 506 |
+
label=f"Processo finalizado: {aplicadas_texto} textos corrigidos, {aplicadas_italico} itálicos aplicados.",
|
| 507 |
state="complete", expanded=False
|
| 508 |
)
|
| 509 |
except Exception as e:
|
|
|
|
| 664 |
)
|
| 665 |
st.write(res.text)
|
| 666 |
except Exception as e:
|
| 667 |
+
st.error(f"Erro ao gerar feedback: {e}")
|