GabrielGD commited on
Commit
a23d2c1
·
verified ·
1 Parent(s): 894a67b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +536 -344
app.py CHANGED
@@ -2,8 +2,6 @@ import os
2
  import io
3
  import re
4
  import json
5
- import logging
6
- from typing import List, Tuple, Optional, Type
7
  import streamlit as st
8
  from docx import Document
9
  from docx.shared import Cm, Pt
@@ -12,41 +10,28 @@ from pydantic import BaseModel
12
  from google import genai
13
  from google.genai import types
14
 
15
- # ─── 1. CONFIGURAÇÕES E LOGGING ───────────────────────────────────────────
16
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
17
-
18
- class AppConfig:
19
- """Centraliza as configurações do aplicativo."""
20
- MODEL_NAME = "gemini-3.5-flash"
21
- MAX_FILE_SIZE_MB = 10
22
- MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024
23
- ALLOWED_EXTENSIONS = ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
24
-
25
  st.set_page_config(page_title="Corretor TCC - UNIFAGOC", page_icon="⚖️", layout="wide")
26
 
27
- # ─── 2. GERENCIAMENTO DE ESTADO ───────────────────────────────────────────
28
- def limpar_estado(chaves: List[str]) -> None:
29
- """Limpa variáveis específicas do estado da sessão."""
30
- for chave in chaves:
31
- if chave in st.session_state:
32
- st.session_state[chave] = None
33
 
34
- # Inicialização do estado
35
- for key in ["resultado_auditoria", "doc_revisado_bytes", "doc_formatado_bytes", "nome_arq_rev", "nome_arq_abnt"]:
36
- if key not in st.session_state:
37
- st.session_state[key] = None
38
 
39
- # ─── 3. SCHEMAS DE DADOS (PYDANTIC) ───────────────────────────────────────
40
  class AuditoriaTCC(BaseModel):
41
  aderencia_percentual: int
42
  diagnostico_geral: str
43
  problema_identificado_no_projeto: str
44
  tcc_respondeu_ao_problema: bool
45
  justificativa_problema: str
46
- objetivos_especificos_identificados: List[str]
47
- objetivos_nao_cumpridos_no_tcc: List[str]
48
- desvios_de_tema_ou_linguica: List[str]
49
- indicios_texto_generico_ia: List[str]
50
  nota_tema_problema: float
51
  nota_introducao_metodo: float
52
  nota_estruturacao: float
@@ -59,309 +44,455 @@ class ErroTexto(BaseModel):
59
  motivo: str
60
 
61
  class RevisaoInteligente(BaseModel):
62
- correcoes: List[ErroTexto]
63
- termos_estrangeiros_para_italico: List[str]
64
 
65
  class ProblemaReferencia(BaseModel):
66
  numero: int
67
- erros: List[str]
68
  elemento_negrito: str
69
 
70
  class AnaliseABNT(BaseModel):
71
- problemas: List[ProblemaReferencia]
72
-
73
- # ─── 4. SERVIÇOS E CLASSES DE NEGÓCIO ─────────────────────────────────────
74
- class GeminiService:
75
- """Encapsula e gerencia as chamadas à API do Gemini."""
76
-
77
- def __init__(self, api_key: str):
78
- if not api_key:
79
- logging.error("GEMINI_API_KEY ausente.")
80
- raise ValueError("Chave da API não encontrada.")
81
- self.client = genai.Client(api_key=api_key)
82
-
83
- def gerar_resposta_estruturada(self, prompt: str, schema: Type[BaseModel], temperature: float = 0.0) -> Optional[BaseModel]:
84
- """Faz a chamada à API garantindo o retorno validado pelo Pydantic."""
85
- config = types.GenerateContentConfig(
86
- temperature=temperature,
87
- response_mime_type="application/json",
88
- response_schema=schema
89
- )
90
- try:
91
- logging.info(f"Enviando prompt ao modelo {AppConfig.MODEL_NAME}...")
92
- res = self.client.models.generate_content(
93
- model=AppConfig.MODEL_NAME,
94
- contents=prompt,
95
- config=config
96
- )
97
- return schema.model_validate_json(res.text)
98
- except Exception as e:
99
- logging.error(f"Erro na API do Gemini: {e}")
100
- raise e
101
-
102
- class DocxFormatter:
103
- """Classe responsável por toda a manipulação e formatação de arquivos DOCX."""
104
-
105
- def __init__(self, file_bytes: bytes):
106
- with io.BytesIO(file_bytes) as doc_stream:
107
- self.doc = Document(doc_stream)
108
-
109
- def to_bytes(self) -> bytes:
110
- """Converte o documento manipulado de volta para bytes."""
111
- with io.BytesIO() as byte_io:
112
- self.doc.save(byte_io)
113
- return byte_io.getvalue()
114
-
115
- def extrair_texto(self) -> str:
116
- """Extrai todo o texto limpo do documento."""
117
- return "\n\n".join([para.text.strip() for para in self.doc.paragraphs if para.text.strip()])
118
-
119
- def estimar_paginas(self) -> int:
120
- """Estima o total de páginas com base na contagem de palavras."""
121
- palavras_totais = sum(
122
- len(para.text.split()) for para in self.doc.paragraphs
123
- if not re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS", para.text, re.IGNORECASE)
124
- )
125
- return max(1, palavras_totais // 350)
126
-
127
- @staticmethod
128
- def _set_run_font(run, nome: str, tamanho_pt: float, negrito: Optional[bool] = None, italico: Optional[bool] = None) -> None:
129
- """Aplica estilos fundamentais a um run do Word."""
130
- run.font.name = nome
131
- run.font.size = Pt(tamanho_pt)
132
- if negrito is not None: run.font.bold = negrito
133
- if italico is not None: run.font.italic = italico
134
-
135
- def aplicar_formatacao_cruzada(self, para, texto_alvo: str, aplicar_italico: bool = False, aplicar_negrito: bool = False) -> int:
136
- """Algoritmo otimizado para aplicar estilos cruzando múltiplos runs."""
137
- aplicacoes = 0
138
- matches = list(re.finditer(r'\b' + re.escape(texto_alvo) + r'\b', para.text, re.IGNORECASE)) if aplicar_italico else [(para.text.find(texto_alvo), para.text.find(texto_alvo) + len(texto_alvo))]
139
-
140
- for match in matches:
141
- pos_ini, pos_fim = match if isinstance(match, tuple) else (match.start(), match.end())
142
- if pos_ini == -1: continue
143
- pos_atual = 0
144
- for run in para.runs:
145
- fim_run = pos_atual + len(run.text)
146
- if pos_atual < pos_fim and fim_run > pos_ini:
147
- if aplicar_italico: run.italic = True
148
- if aplicar_negrito: run.bold = True
149
- aplicacoes += 1
150
- pos_atual += len(run.text)
151
- return aplicacoes
152
-
153
- def substituir_texto(self, para, original: str, corrigido: str) -> int:
154
- """Substitui strings com segurança, evitando perda de estilo de runs."""
155
- if original not in para.text: return 0
156
  for run in para.runs:
157
- if original in run.text:
158
- run.text = run.text.replace(original, corrigido, 1)
159
- return 1
160
- estilo_base = para.runs[0].style if para.runs else None
161
- texto_completo = para.text.replace(original, corrigido, 1)
162
- para.clear()
163
- novo_run = para.add_run(texto_completo)
164
- if estilo_base: novo_run.style = estilo_base
165
- return 1
166
-
167
- def formatar_estrutura_unifagoc(self) -> None:
168
- """Aplica a geometria física e a máquina de estados para formatar o TCC."""
169
- # Margens
170
- for section in self.doc.sections:
171
- section.page_height, section.page_width = Cm(29.7), Cm(21.0)
172
- section.top_margin, section.left_margin = Cm(3.0), Cm(3.0)
173
- section.bottom_margin, section.right_margin = Cm(2.0), Cm(2.0)
174
- section.header_distance, section.footer_distance = Cm(0.5), Cm(0.5)
175
-
176
- fase_atual = "PRE_RESUMO"
177
- for i, para in enumerate(self.doc.paragraphs):
178
- texto = para.text.strip()
179
- if not texto: continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
- texto_upper = texto.upper()
182
- pf = para.paragraph_format
183
-
184
- # MÁQUINA DE ESTADOS
185
- if texto_upper == "RESUMO": fase_atual = "RESUMO_LBL"
186
- elif fase_atual == "RESUMO_LBL": fase_atual = "RESUMO_BODY"
187
- if texto_upper.startswith("PALAVRAS-CHAVE"): fase_atual = "PALAVRAS_CH"
188
- elif re.match(r"^(?:INTRODU[ÇC]ÃO|1[\s\.])", texto_upper): fase_atual = "CORPO"
189
- if bool(re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS\b", texto_upper)): fase_atual = "REF_TITLE"
190
- elif fase_atual == "REF_TITLE": fase_atual = "REF_ENTRY"
191
-
192
- # APLICAÇÃO DE ESTILOS
193
- if fase_atual == "PRE_RESUMO":
194
- is_titulo = (i == 0 or (texto.isupper() and len(texto) < 150))
195
  pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
196
- pf.first_line_indent, pf.left_indent, pf.space_before, pf.space_after = None, None, Pt(0), Pt(0)
197
- pf.line_spacing = 1.5 if is_titulo else None
 
 
 
198
  for run in para.runs:
199
- self._set_run_font(run, 'Calibri', 14 if is_titulo else 12, negrito=is_titulo)
200
-
201
- elif fase_atual == "RESUMO_LBL":
202
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.JUSTIFY, None, Pt(12), Pt(0), 1.5
203
- for run in para.runs: self._set_run_font(run, 'Calibri', 11, negrito=True, italico=False)
204
-
205
- elif fase_atual == "RESUMO_BODY":
206
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.JUSTIFY, None, Pt(0), Pt(0), 1.5
207
- for run in para.runs: self._set_run_font(run, 'Calibri', 11, negrito=False, italico=True)
208
-
209
- elif fase_atual == "PALAVRAS_CH":
210
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.JUSTIFY, None, Pt(6), Pt(0), 1.5
211
  for run in para.runs:
212
- self._set_run_font(run, 'Calibri', 11, negrito=("PALAVRAS-CHAVE" in run.text.upper()), italico=False)
213
-
214
- elif fase_atual == "CORPO":
215
- if texto.isupper() and len(texto) < 120:
216
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.JUSTIFY, None, Pt(0), Pt(12), 1.5
217
- for run in para.runs: self._set_run_font(run, 'Calibri', 12, negrito=True)
218
- elif pf.left_indent is not None and pf.left_indent >= Cm(3.5):
219
- pf.alignment, pf.first_line_indent, pf.left_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.JUSTIFY, None, Cm(4.0), Pt(6), Pt(6), 1.0
220
- for run in para.runs: self._set_run_font(run, 'Calibri', 11)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  else:
222
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.JUSTIFY, Cm(1.25), Pt(0), Pt(0), 1.5
223
- for run in para.runs: self._set_run_font(run, 'Calibri', 12)
224
-
225
- elif fase_atual == "REF_TITLE":
226
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.CENTER, None, Pt(0), Pt(0), 1.5
227
- for run in para.runs: self._set_run_font(run, 'Calibri', 12, negrito=True)
228
-
229
- elif fase_atual == "REF_ENTRY":
230
- pf.alignment, pf.first_line_indent, pf.space_before, pf.space_after, pf.line_spacing = WD_ALIGN_PARAGRAPH.LEFT, None, Pt(6), Pt(0), 1.0
231
- for run in para.runs: self._set_run_font(run, 'Calibri', 11)
232
-
233
- # ─── 5. VALIDADORES (SEGURANÇA) ───────────────────────────────────────────
234
- def validar_arquivo(arquivo) -> bool:
235
- """Verifica tipo MIME e limite de tamanho do arquivo."""
236
- if arquivo is None: return False
237
- if arquivo.size > AppConfig.MAX_FILE_SIZE_BYTES:
238
- st.error(f"Arquivo excedeu o limite de {AppConfig.MAX_FILE_SIZE_MB}MB.")
239
- return False
240
- if arquivo.type not in AppConfig.ALLOWED_EXTENSIONS:
241
- st.error("Formato inválido. Envie um arquivo .docx válido.")
242
- return False
243
- return True
244
-
245
- @st.cache_data(show_spinner=False)
246
- def ler_texto_cache(file_bytes: bytes) -> str:
247
- """Extrai texto com cache para otimizar processamentos múltiplos."""
248
- return DocxFormatter(file_bytes).extrair_texto()
249
-
250
- # ─── 6. INTERFACE PRINCIPAL DO STREAMLIT ──────────────────────────────────
251
- def main():
252
- # Inicializa serviço da IA
253
- try:
254
- ia_service = GeminiService(os.environ.get("GEMINI_API_KEY", ""))
255
- except ValueError:
256
- st.stop()
257
-
258
- st.title("⚖️ Assistente Acadêmico - Direito UNIFAGOC")
259
- aba_auditoria, aba_revisao, aba_abnt, aba_prompt, aba_feedback = st.tabs([
260
- "🔍 Auditoria e Notas", "🧠 Revisão Inteligente", "📐 Formatação ABNT", "🤖 Prompt Mestre", "👨‍🏫 Feedback Professor"
261
- ])
262
-
263
- # ==========================================================================
264
- # ABA 1: AUDITORIA
265
- # ==========================================================================
266
- with aba_auditoria:
267
- with st.expander("ℹ️ Como funciona a Auditoria?", expanded=False):
268
- st.write("Cruza o **Pré-Projeto** com o **TCC** para identificar fuga do tema, sugerir notas e verificar a resposta ao problema de pesquisa.")
269
-
270
- fase_tcc = st.radio("Fase atual:", ["TCC 1 (Apenas Introdução e Capítulo 1)", "TCC 2 (TCC Completo)"], horizontal=True, on_change=limpar_estado, args=(["resultado_auditoria"],))
271
- c1, c2 = st.columns(2)
272
- with c1: arq_projeto = st.file_uploader("1. Pré-Projeto (.docx)", type=["docx"], key="proj", on_change=limpar_estado, args=(["resultado_auditoria"],))
273
- with c2: arq_tcc = st.file_uploader("2. TCC (.docx)", type=["docx"], key="tcc_aud", on_change=limpar_estado, args=(["resultado_auditoria"],))
274
-
275
- if st.button("🔍 Iniciar Auditoria", type="primary") and validar_arquivo(arq_projeto) and validar_arquivo(arq_tcc):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  with st.status("A analisar argumentação jurídica...", expanded=True) as status:
277
- texto_projeto = ler_texto_cache(arq_projeto.getvalue())
278
- texto_tcc = ler_texto_cache(arq_tcc.getvalue())
279
-
280
- regra_fase = "TCC 1: NÃO penalize ausência de Resumo e Conclusão." if "TCC 1" in fase_tcc else "TCC 2: Exija o trabalho completo."
281
- prompt = f"Professor UNIFAGOC.\n{regra_fase}\nPROJETO:\n{texto_projeto}\n\nTCC:\n{texto_tcc}\nTAREFA: Avalie cruzamento de dados e distribua 80 pontos rigorosamente."
282
-
 
 
 
 
 
 
 
 
 
 
 
 
283
  try:
284
- dados = ia_service.gerar_resposta_estruturada(prompt, AuditoriaTCC)
285
- st.session_state.resultado_auditoria = dados.model_dump()
286
- status.update(label="Avaliação concluída!", state="complete", expanded=False)
287
- st.toast("✅ Auditoria finalizada com sucesso!")
288
- except Exception:
 
 
 
 
 
 
 
289
  status.update(label="Falha na avaliação.", state="error")
290
-
291
- if st.session_state.resultado_auditoria:
292
- dados = st.session_state.resultado_auditoria
293
- nota_total = sum([dados.get("nota_tema_problema", 0), dados.get("nota_introducao_metodo", 0), dados.get("nota_estruturacao", 0), dados.get("nota_formatacao_abnt", 0)])
294
- st.header("🏆 Avaliação da Banca UNIFAGOC")
295
- cc1, cc2, cc3, cc4 = st.columns(4)
296
- cc1.metric("Tema/Problema", f"{dados.get('nota_tema_problema')}/20")
297
- cc2.metric("Intro/Método", f"{dados.get('nota_introducao_metodo')}/20")
298
- cc3.metric("Estrutura", f"{dados.get('nota_estruturacao')}/20")
299
- cc4.metric("ABNT", f"{dados.get('nota_formatacao_abnt')}/20")
300
- st.info(f"**NOTA: {nota_total}/80 pontos**\n*Parecer:* {dados.get('justificativa_notas_banca')}")
301
-
302
- # ==========================================================================
303
- # ABA 2: REVISÃO INTELIGENTE
304
- # ==========================================================================
305
- with aba_revisao:
306
- st.write("Identifica **Ortografia**, **CAIXA ALTA** indevida e **Itálico** em latim/jargões.")
307
- arq_rev = st.file_uploader("Envie o TCC (.docx)", type=["docx"], key="rev", on_change=limpar_estado, args=(["doc_revisado_bytes"],))
308
-
309
- if st.button("🧠 Realizar Revisão") and validar_arquivo(arq_rev):
310
- with st.status("Lendo e corrigindo o documento...", expanded=True) as status:
311
- file_bytes = arq_rev.getvalue()
312
- texto = ler_texto_cache(file_bytes)
313
-
314
- prompt_rev = f"Localize erros ortográficos, textos em CAIXA ALTA no corpo e termos latinos que exigem itálico.\nTEXTO:\n{texto}"
315
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  try:
317
- dados = ia_service.gerar_resposta_estruturada(prompt_rev, RevisaoInteligente, temperature=0.1)
318
- formatter = DocxFormatter(file_bytes)
319
- aplicadas = 0
320
-
321
- if dados.correcoes:
322
- for c in dados.correcoes:
323
- for para in formatter.doc.paragraphs:
324
- aplicadas += formatter.substituir_texto(para, c.original, c.corrigido)
325
-
326
- if dados.termos_estrangeiros_para_italico:
327
- for termo in dados.termos_estrangeiros_para_italico:
328
- for para in formatter.doc.paragraphs:
329
- aplicadas += formatter.aplicar_formatacao_cruzada(para, termo, aplicar_italico=True)
330
-
331
- st.session_state.doc_revisado_bytes = formatter.to_bytes()
 
 
 
 
 
 
 
 
 
 
 
332
  st.session_state.nome_arq_rev = f"{arq_rev.name.replace('.docx', '')}_Revisado.docx"
333
- status.update(label=f"{aplicadas} intervenções aplicadas.", state="complete", expanded=False)
334
- st.toast("✅ Documento revisado com sucesso!")
335
- except Exception:
 
 
336
  status.update(label="Erro no processamento.", state="error")
 
 
 
 
 
 
 
 
 
337
 
338
- if st.session_state.doc_revisado_bytes:
339
- st.download_button("⬇️ Baixar TCC Revisado (.docx)", data=st.session_state.doc_revisado_bytes, file_name=st.session_state.nome_arq_rev, mime=AppConfig.ALLOWED_EXTENSIONS[0])
340
-
341
- # ==========================================================================
342
- # ABA 3: FORMATAÇÃO ABNT
343
- # ==========================================================================
344
- with aba_abnt:
345
- st.write("Aplica as regras físicas (Calibri, margens 3x2, recuos) e usa IA para negrito em referências.")
346
- arq_abnt = st.file_uploader("Envie o TCC (.docx)", type=["docx"], key="abnt_file", on_change=limpar_estado, args=(["doc_formatado_bytes"],))
347
-
348
- if st.button("📐 Formatar TCC") and validar_arquivo(arq_abnt):
349
- with st.status("Reestruturando geometria do Word...", expanded=True) as status:
350
- formatter = DocxFormatter(arq_abnt.getvalue())
351
-
352
- paginas = formatter.estimar_paginas()
353
- if paginas > 18: st.warning(f"🚨 Extensão: {paginas} págs (Limite: 18).")
354
- else: st.info(f"📄 Extensão estimada: {paginas} páginas.")
 
 
 
355
 
356
- formatter.formatar_estrutura_unifagoc()
 
357
 
358
- # Processamento de Referências
359
  refs_limpas = []
360
  em_refs = False
361
- for i, para in enumerate(formatter.doc.paragraphs):
362
  txt = para.text.strip()
363
  if not txt: continue
364
- if re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS\b", txt, re.IGNORECASE): em_refs = True; continue
 
365
  if em_refs:
366
  if len(txt) < 120 and txt.isupper() and not txt[0].isdigit(): break
367
  refs_limpas.append((i, txt))
@@ -370,49 +501,110 @@ def main():
370
 
371
  if refs_limpas:
372
  texto_refs = "\n".join(f"[{idx}] {txt}" for idx, txt in refs_limpas)
373
- prompt_abnt = f"Analise as referências (ABNT 6023). Extraia o trecho EXATO (título da obra) para negrito.\nREFERÊNCIAS:\n{texto_refs}"
 
 
 
 
 
 
374
  try:
375
- dados = ia_service.gerar_resposta_estruturada(prompt_abnt, AnaliseABNT)
376
- mapa_paras = {idx: formatter.doc.paragraphs[idx] for idx, _ in refs_limpas}
377
- negs = 0
378
- for prob in dados.problemas:
379
- elem = prob.elemento_negrito.strip()
380
- if elem and prob.numero in mapa_paras:
381
- negs += formatter.aplicar_formatacao_cruzada(mapa_paras[prob.numero], elem, aplicar_negrito=True)
 
 
 
 
 
 
382
 
383
- status.update(label=f"TCC Formatado! {negs} referências destacadas.", state="complete", expanded=False)
384
- st.toast("✅ Formatação ABNT concluída!")
385
- except Exception:
386
- status.update(label="Formatação física concluída (Erro na IA de referências).", state="complete")
 
 
 
 
 
 
 
 
 
 
 
387
  else:
388
- status.update(label="Formatação física concluída (Sem referências).", state="complete")
389
-
390
- st.session_state.doc_formatado_bytes = formatter.to_bytes()
391
-
392
- if st.session_state.doc_formatado_bytes:
393
- st.download_button("⬇️ Baixar TCC Formatado (.docx)", data=st.session_state.doc_formatado_bytes, file_name=st.session_state.nome_arq_abnt, mime=AppConfig.ALLOWED_EXTENSIONS[0])
394
-
395
- # ==========================================================================
396
- # ABA 4 & 5: PROMPT E FEEDBACK (Estáticos/Leitura Rápida)
397
- # ==========================================================================
398
- with aba_prompt:
399
- st.write("Copie o prompt abaixo e cole no ChatGPT/Claude antes de gerar seu texto:")
400
- st.code("""Atue como revisor ABNT (UNIFAGOC).\n1. Estruture com INTRODUÇÃO, Capítulos, REFERÊNCIAS.\n2. Termos latinos em *itálico*.\n3. Citações longas: use [CITAÇÃO LONGA AQUI].\n4. Não invente fontes.\nTEXTO:\n[COLE AQUI]""", language="markdown")
401
 
402
- with aba_feedback:
403
- st.write("Gere um relatório sobre a fluidez dos parágrafos e vícios de escrita (ex: excesso de Apud).")
404
- arq_fb = st.file_uploader("Enviar TCC", type=["docx"], key="feedback")
405
- if st.button("📊 Gerar Feedback") and validar_arquivo(arq_fb):
406
- with st.spinner("Analisando estilo literário..."):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
  try:
408
- texto = ler_texto_cache(arq_fb.getvalue())
409
- prompt_fb = f"Professor UNIFAGOC. Avalie: Parágrafos curtos? Excesso de Apud? Leis iniciam com BRASIL? Pontos fortes/fracos.\nTEXTO:\n{texto}"
410
- # Usa o cliente base diretamente para resposta não-estruturada (texto livre)
411
- res = ia_service.client.models.generate_content(model=AppConfig.MODEL_NAME, contents=prompt_fb)
 
412
  st.write(res.text)
413
- st.toast("✅ Feedback gerado!")
414
  except Exception as e:
415
- st.error(f"Erro ao gerar feedback: {e}")
416
-
417
- if __name__ == "__main__":
418
- main()
 
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
  from google import genai
11
  from google.genai import types
12
 
13
+ # ─── 1. CONFIGURAÇÃO DA PÁGINA E ESTADO ───────────────────────────────────
 
 
 
 
 
 
 
 
 
14
  st.set_page_config(page_title="Corretor TCC - UNIFAGOC", page_icon="⚖️", layout="wide")
15
 
16
+ def reset_estado(chave):
17
+ if chave in st.session_state:
18
+ st.session_state[chave] = None
 
 
 
19
 
20
+ if "resultado_auditoria" not in st.session_state: st.session_state.resultado_auditoria = None
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
27
  diagnostico_geral: str
28
  problema_identificado_no_projeto: str
29
  tcc_respondeu_ao_problema: bool
30
  justificativa_problema: str
31
+ objetivos_especificos_identificados: list[str]
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
 
44
  motivo: str
45
 
46
  class RevisaoInteligente(BaseModel):
47
+ correcoes: list[ErroTexto]
48
+ termos_estrangeiros_para_italico: list[str]
49
 
50
  class ProblemaReferencia(BaseModel):
51
  numero: int
52
+ erros: list[str]
53
  elemento_negrito: str
54
 
55
  class AnaliseABNT(BaseModel):
56
+ problemas: list[ProblemaReferencia]
57
+
58
+ # ─── 3. AUTENTICAÇÃO E CACHE ───────────────────────────────────────────────
59
+ @st.cache_resource
60
+ def get_client():
61
+ api_key = os.environ.get("GEMINI_API_KEY")
62
+ if not api_key:
63
+ st.error("❌ ERRO: A variável de ambiente GEMINI_API_KEY não foi encontrada nos Secrets.")
64
+ st.stop()
65
+ return genai.Client(api_key=api_key)
66
+
67
+ client = get_client()
68
+
69
+ # ─── 4. MANIPULAÇÃO AVANÇADA DE DOCUMENTOS (DOCX) ─────────────────────────
70
+ def extrair_texto_docx(arquivo_upload) -> str:
71
+ doc = Document(arquivo_upload)
72
+ return "\n\n".join([para.text.strip() for para in doc.paragraphs if para.text.strip()])
73
+
74
+ def docx_to_bytes(doc: Document) -> bytes:
75
+ byte_io = io.BytesIO()
76
+ doc.save(byte_io)
77
+ return byte_io.getvalue()
78
+
79
+ def estimar_paginas(doc: Document) -> int:
80
+ palavras_totais = sum(
81
+ len(para.text.split()) for para in doc.paragraphs
82
+ if not re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS", para.text, re.IGNORECASE)
83
+ )
84
+ return max(1, palavras_totais // 350)
85
+
86
+ def substituir_texto_cross_run(para, original, corrigido) -> int:
87
+ if original not in para.text: return 0
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
+ estilo_base = para.runs[0].style if para.runs else None
93
+ texto_completo = para.text.replace(original, corrigido, 1)
94
+ para.clear()
95
+ novo_run = para.add_run(texto_completo)
96
+ if estilo_base: novo_run.style = estilo_base
97
+ return 1
98
+
99
+ def formatacao_cruzada_indices(para, texto_alvo, aplicar_italico=False, aplicar_negrito=False) -> int:
100
+ aplicacoes = 0
101
+ if aplicar_italico:
102
+ matches = list(re.finditer(r'\b' + re.escape(texto_alvo) + r'\b', para.text, re.IGNORECASE))
103
+ else:
104
+ idx = para.text.find(texto_alvo)
105
+ matches = [(idx, idx + len(texto_alvo))] if idx != -1 else []
106
+
107
+ for match in matches:
108
+ pos_ini, pos_fim = match if isinstance(match, tuple) else (match.start(), match.end())
109
+ if pos_ini == -1: continue
110
+ pos_atual = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  for run in para.runs:
112
+ fim_run = pos_atual + len(run.text)
113
+ if pos_atual < pos_fim and fim_run > pos_ini:
114
+ if aplicar_italico: run.italic = True
115
+ if aplicar_negrito: run.bold = True
116
+ aplicacoes += 1
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)
130
+ section.top_margin = Cm(3.0)
131
+ section.left_margin = Cm(3.0)
132
+ section.bottom_margin = Cm(2.0)
133
+ section.right_margin = Cm(2.0)
134
+ section.header_distance = Cm(0.5)
135
+ section.footer_distance = Cm(0.5)
136
+
137
+ fase_atual = "PRE_RESUMO" # Controla o fluxo da leitura
138
+
139
+ for i, para in enumerate(doc.paragraphs):
140
+ texto = para.text.strip()
141
+ if not texto: continue
142
+
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":
150
+ fase_atual = "RESUMO_BODY"
151
+
152
+ if texto_upper.startswith("PALAVRAS-CHAVE"):
153
+ fase_atual = "PALAVRAS_CH"
154
+ elif re.match(r"^(?:INTRODU[ÇC]ÃO|1[\s\.])", texto_upper):
155
+ fase_atual = "CORPO"
156
 
157
+ is_titulo_refs = bool(re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS\b", texto_upper))
158
+ if is_titulo_refs:
159
+ fase_atual = "REF_TITLE"
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
171
+ pf.space_before = Pt(0)
172
+ pf.space_after = Pt(0)
173
+ pf.line_spacing = 1.5
174
  for run in para.runs:
175
+ run.font.name = 'Calibri'
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 # Correção crítica apontada
 
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
196
+ pf.space_before = Pt(12)
197
+ pf.space_after = Pt(0)
198
+ pf.line_spacing = 1.5
199
+ for run in para.runs:
200
+ run.font.name = 'Calibri'
201
+ run.font.size = Pt(11)
202
+ run.font.bold = True
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
210
+ pf.space_before = Pt(0)
211
+ pf.space_after = Pt(0)
212
+ pf.line_spacing = 1.5
213
+ for run in para.runs:
214
+ run.font.name = 'Calibri'
215
+ run.font.size = Pt(11)
216
+ run.font.italic = True
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
224
+ pf.space_before = Pt(6)
225
+ pf.space_after = Pt(0)
226
+ pf.line_spacing = 1.5
227
+ for run in para.runs:
228
+ run.font.name = 'Calibri'
229
+ run.font.size = Pt(11)
230
+ if "PALAVRAS-CHAVE" in run.text.upper():
231
+ run.font.bold = True
232
+ run.font.italic = False
233
  else:
234
+ run.font.bold = False
235
+ run.font.italic = False
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
243
+ pf.space_before = Pt(0)
244
+ pf.space_after = Pt(12)
245
+ pf.line_spacing = 1.5
246
+ for run in para.runs:
247
+ run.font.name = 'Calibri'
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)
255
+ pf.space_before = Pt(6)
256
+ pf.space_after = Pt(6)
257
+ pf.line_spacing = 1.0
258
+ for run in para.runs:
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
266
+ pf.space_before = Pt(0)
267
+ pf.space_after = Pt(0)
268
+ pf.line_spacing = 1.5
269
+ for run in para.runs:
270
+ run.font.name = 'Calibri'
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
278
+ pf.space_before = Pt(0)
279
+ pf.space_after = Pt(0)
280
+ pf.line_spacing = 1.5
281
+ for run in para.runs:
282
+ run.font.name = 'Calibri'
283
+ run.font.size = Pt(12)
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
291
+ pf.space_before = Pt(6)
292
+ pf.space_after = Pt(0)
293
+ pf.line_spacing = 1.0
294
+ for run in para.runs:
295
+ run.font.name = 'Calibri'
296
+ run.font.size = Pt(11)
297
+
298
+ # ─── 5. INTERFACE PRINCIPAL (ABAS) ────────────────────────────────────────
299
+ st.title("⚖️ Assistente Acadêmico - Direito UNIFAGOC")
300
+ aba_auditoria, aba_revisao, aba_abnt, aba_prompt, aba_feedback = st.tabs([
301
+ "🔍 Auditoria e Notas",
302
+ "🧠 Revisão Inteligente",
303
+ "📐 Formatação ABNT",
304
+ "🤖 Prompt Mestre",
305
+ "👨‍🏫 Feedback Professor"
306
+ ])
307
+
308
+ # ==============================================================================
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)
316
+ with col1: arq_projeto = st.file_uploader("1. Pré-Projeto (.docx)", type=["docx"], key="proj", on_change=reset_estado, args=("resultado_auditoria",))
317
+ with col2: arq_tcc = st.file_uploader("2. TCC (.docx)", type=["docx"], key="tcc_aud", on_change=reset_estado, args=("resultado_auditoria",))
318
+
319
+ if st.button("🔍 Iniciar Auditoria e Avaliação", type="primary"):
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: Distribua 80 pontos rigorosamente de acordo com os critérios da ficha UNIFAGOC."
339
+ )
340
+
341
+ st.write("A submeter dados à IA do Google...")
342
  try:
343
+ res = client.models.generate_content(
344
+ model="gemini-3.5-flash",
345
+ contents=prompt,
346
+ config=types.GenerateContentConfig(
347
+ temperature=0.0,
348
+ response_mime_type="application/json",
349
+ response_schema=AuditoriaTCC
350
+ )
351
+ )
352
+ st.session_state.resultado_auditoria = json.loads(res.text)
353
+ status.update(label="Avaliação da Banca concluída!", state="complete", expanded=False)
354
+ except Exception as e:
355
  status.update(label="Falha na avaliação.", state="error")
356
+ st.error(f"Erro: {e}")
357
+
358
+ if st.session_state.resultado_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("nota_introducao_metodo", 0),
364
+ dados.get("nota_estruturacao", 0),
365
+ dados.get("nota_formatacao_abnt", 0)
366
+ ])
367
+
368
+ c1, c2, c3, c4 = st.columns(4)
369
+ c1.metric("Tema/Problema", f"{dados.get('nota_tema_problema')}/20")
370
+ c2.metric("Intro/Método", f"{dados.get('nota_introducao_metodo')}/20")
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 foram abordados.")
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}")
398
+ for ia in dados.get("indicios_texto_generico_ia", []):
399
+ st.error(f"Indício de IA/Texto Genérico: {ia}")
400
+
401
+ # ==============================================================================
402
+ # ABA 2: REVISÃO TEXTUAL INTELIGENTE
403
+ # ==============================================================================
404
+ with aba_revisao:
405
+ st.markdown("A IA analisa o contexto para corrigir **Ortografia**, **CAIXA ALTA** indevida e aplica **Itálico** em termos latinos/estrangeiros.")
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 Inteligência de Revisão...", expanded=True) as status:
411
+ st.write("A ler o documento completo...")
412
+ texto = extrair_texto_docx(arq_rev)
413
+ prompt_rev = (
414
+ "Localize erros ortográficos, textos em CAIXA ALTA no corpo do texto e "
415
+ "termos estrangeiros (ex: habeas corpus) que precisam de itálico.\n"
416
+ f"TEXTO:\n{texto}"
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",
423
+ contents=prompt_rev,
424
+ config=types.GenerateContentConfig(
425
+ temperature=0.1,
426
+ response_mime_type="application/json",
427
+ response_schema=RevisaoInteligente
428
+ )
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
+
436
+ if dados.get("correcoes"):
437
+ for c in dados["correcoes"]:
438
+ for para in doc_rev.paragraphs:
439
+ aplicadas_texto += substituir_texto_cross_run(para, c["original"], c["corrigido"])
440
+
441
+ if dados.get("termos_estrangeiros_para_italico"):
442
+ for termo in dados["termos_estrangeiros_para_italico"]:
443
+ for para in doc_rev.paragraphs:
444
+ aplicadas_italico += formatacao_cruzada_indices(para, termo, aplicar_italico=True)
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 com {aplicadas_texto + aplicadas_italico} intervenções automáticas.",
450
+ state="complete", expanded=False
451
+ )
452
+ except Exception as e:
453
  status.update(label="Erro no processamento.", state="error")
454
+ st.error(f"Erro: {e}")
455
+
456
+ if st.session_state.doc_revisado_bytes:
457
+ st.download_button(
458
+ "⬇️ Baixar TCC Revisado (.docx)",
459
+ data=st.session_state.doc_revisado_bytes,
460
+ file_name=st.session_state.nome_arq_rev,
461
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
462
+ )
463
 
464
+ # ==============================================================================
465
+ # ABA 3: FORMATAÇÃO TOTAL ABNT (UNIFAGOC)
466
+ # ==============================================================================
467
+ with aba_abnt:
468
+ st.markdown(
469
+ "Motor de formatação **fiel ao template UNIFAGOC**. "
470
+ "Aplica as regras corretas de Calibri, margens, espaçamentos e estilos corrigidos."
471
+ )
472
+ arq_abnt = st.file_uploader("Envie o TCC (.docx)", type=["docx"], key="abnt_file", on_change=reset_estado, args=("doc_formatado_bytes",))
473
+
474
+ if st.button("📐 Formatar TCC"):
475
+ if arq_abnt:
476
+ with st.status("A reestruturar formatação conforme template UNIFAGOC...", expanded=True) as status:
477
+ doc_abnt = Document(arq_abnt)
478
+
479
+ paginas_estimadas = estimar_paginas(doc_abnt)
480
+ if paginas_estimadas > 18:
481
+ st.warning(f"🚨 Extensão de {paginas_estimadas} páginas. O limite recomendado é 18.")
482
+ else:
483
+ st.info(f"📄 Extensão estimada: {paginas_estimadas} páginas.")
484
 
485
+ st.write("A aplicar regras rigorosas do template corrigido...")
486
+ aplicar_formatacao_unifagoc_abnt(doc_abnt)
487
 
488
+ st.write("A analisar Referências Bibliográficas com IA...")
489
  refs_limpas = []
490
  em_refs = False
491
+ for i, para in enumerate(doc_abnt.paragraphs):
492
  txt = para.text.strip()
493
  if not txt: continue
494
+ if re.search(r"^(?:\d+\.?\s*)?REFER[ÊE]NCIAS\b", txt, re.IGNORECASE):
495
+ em_refs = True; continue
496
  if em_refs:
497
  if len(txt) < 120 and txt.isupper() and not txt[0].isdigit(): break
498
  refs_limpas.append((i, txt))
 
501
 
502
  if refs_limpas:
503
  texto_refs = "\n".join(f"[{idx}] {txt}" for idx, txt in refs_limpas)
504
+ prompt_abnt = (
505
+ "Analise as referências (ABNT 6023:2018). "
506
+ "Para cada uma, devolva o índice exato entre colchetes como 'numero', "
507
+ "e extraia o trecho EXATO (título do livro ou nome da revista/periódico) "
508
+ "que deve receber negrito.\n"
509
+ f"REFERÊNCIAS:\n{texto_refs}"
510
+ )
511
  try:
512
+ res = client.models.generate_content(
513
+ model="gemini-3.5-flash",
514
+ contents=prompt_abnt,
515
+ config=types.GenerateContentConfig(
516
+ temperature=0.0,
517
+ response_mime_type="application/json",
518
+ response_schema=AnaliseABNT
519
+ )
520
+ )
521
+ dados_abnt = json.loads(res.text)
522
+
523
+ mapa_idx_para = {idx: doc_abnt.paragraphs[idx] for idx, _ in refs_limpas if idx < len(doc_abnt.paragraphs)}
524
+ negs_aplicados = 0
525
 
526
+ for problema in dados_abnt.get("problemas", []):
527
+ num = problema.get("numero")
528
+ elem = problema.get("elemento_negrito", "").strip()
529
+ if elem and num in mapa_idx_para:
530
+ negs_aplicados += formatacao_cruzada_indices(mapa_idx_para[num], elem, aplicar_negrito=True)
531
+
532
+ st.session_state.doc_formatado_bytes = docx_to_bytes(doc_abnt)
533
+ status.update(
534
+ label=f"TCC formatado! {negs_aplicados} negritos aplicados nas referências.",
535
+ state="complete", expanded=False
536
+ )
537
+ except Exception as e:
538
+ st.session_state.doc_formatado_bytes = docx_to_bytes(doc_abnt)
539
+ status.update(label="Formatação aplicada (negrito de referências ignorado).", state="complete")
540
+ st.warning(f"Aviso na análise ABNT: {e}")
541
  else:
542
+ st.session_state.doc_formatado_bytes = docx_to_bytes(doc_abnt)
543
+ status.update(label="Formatação aplicada (nenhuma referência encontrada).", state="complete")
544
+
545
+ if st.session_state.doc_formatado_bytes:
546
+ st.download_button(
547
+ "⬇️ Baixar TCC Final Formatado (.docx)",
548
+ data=st.session_state.doc_formatado_bytes,
549
+ file_name=st.session_state.nome_arq_abnt,
550
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
551
+ )
 
 
 
552
 
553
+ # ==============================================================================
554
+ # ABA 4: PROMPT MESTRE
555
+ # ==============================================================================
556
+ with aba_prompt:
557
+ st.markdown("### 🤖 Prompt Mestre - Padrão UNIFAGOC")
558
+ st.write("Vai usar o ChatGPT, Gemini ou Claude para gerar ou rever o seu texto? Copie o prompt abaixo e cole na IA antes de enviar o seu rascunho.")
559
+
560
+ prompt_pronto = """Atue como um revisor académico especialista em formatação ABNT e nas diretrizes institucionais do curso de Direito da UNIFAGOC.
561
+
562
+ Vou-lhe enviar o rascunho do meu texto. A sua tarefa é revisá-lo e reescrevê-lo garantindo a linguagem formal, impessoal e o rigor do vocabulário jurídico.
563
+
564
+ Siga ESTRITAMENTE estas regras estruturais ao gerar a resposta:
565
+ 1. ESTRUTURA DE SECÇÕES: Organize o texto utilizando os títulos padrão exigidos: INTRODUÇÃO, secções numeradas (ex: 1. TÍTULO), CONSIDERAÇÕES FINAIS e REFERÊNCIAS.
566
+ 2. RESUMO (se aplicável): Deve ser redigido em parágrafo único, contendo problema de pesquisa, objetivo, método e resultados, com limite máximo de 150 palavras. Logo abaixo, inclua de 3 a 5 palavras-chave separadas por ponto e com a primeira letra de cada palavra em maiúscula.
567
+ 3. TERMOS ESTRANGEIROS: Identifique termos em latim ou língua estrangeira (ex: habeas corpus, fake news) e coloque-os em *itálico*.
568
+ 4. CITAÇÕES CURTAS: Citações diretas com até 3 linhas devem vir entre aspas duplas no corpo do texto.
569
+ 5. CITAÇÕES LONGAS: Citações diretas com mais de 3 linhas devem vir em parágrafo separado. Inicie o parágrafo com a tag [CITAÇÃO LONGA AQUI - RECUO] para posterior formatação.
570
+ 6. REFERÊNCIAS: Formate no padrão ABNT NBR 6023:2018. Gere as referências alinhadas à esquerda e sem recuos laterais. Aplique **negrito** apenas no elemento de destaque (título do livro ou nome do periódico).
571
+ 7. INTEGRIDADE: Não invente leis, jurisprudências ou doutrinas. Baseie-se exclusivamente no conteúdo e contexto fornecidos.
572
+
573
+ Aqui está o meu texto:
574
+ [COLE O SEU TEXTO AQUI]"""
575
+
576
+ st.code(prompt_pronto, language="markdown")
577
+
578
+ # ==============================================================================
579
+ # ABA 5: FEEDBACK ACADÉMICO (O Olhar do Professor)
580
+ # ==============================================================================
581
+ with aba_feedback:
582
+ st.markdown("### 👨‍🏫 Feedback do Professor Examinador")
583
+ st.write("Envie o seu TCC para receber uma análise crítica do fluxo de escrita, fluidez dos parágrafos e conformidade com as exigências da banca.")
584
+
585
+ arq_feedback = st.file_uploader("Envie o seu TCC (.docx) para avaliação", type=["docx"], key="feedback")
586
+
587
+ if st.button("📊 Gerar Relatório de Feedback"):
588
+ if arq_feedback:
589
+ with st.spinner("A avaliar o estilo académico e a fluidez do texto..."):
590
+ texto = extrair_texto_docx(arq_feedback)
591
+
592
+ prompt_fb = f"""
593
+ Você é o Professor Examinador da UNIFAGOC. Analise o TCC abaixo e forneça um feedback estruturado:
594
+ 1. ESTRUTURA: O texto possui parágrafos curtos e abruptos? Há fluidez entre os capítulos?
595
+ 2. CITAÇÕES E ABUSOS: O aluno usa excesso de 'Apud'? Ele cita leis corretamente começando com 'BRASIL'?
596
+ 3. PONTOS FORTES e PONTOS DE ATENÇÃO: Destaque o que está excelente e o que precisa de ser refatorado imediatamente.
597
+ 4. FORMAÇÃO: O aluno misturou fontes ou fez formatações erradas ao longo da redação?
598
+
599
+ TEXTO: {texto}
600
+ """
601
+
602
  try:
603
+ res = client.models.generate_content(
604
+ model="gemini-3.5-flash",
605
+ contents=prompt_fb,
606
+ config=types.GenerateContentConfig(temperature=0.2)
607
+ )
608
  st.write(res.text)
 
609
  except Exception as e:
610
+ st.error(f"Erro ao gerar feedback: {e}")