Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -4,68 +4,33 @@ from huggingface_hub import InferenceClient
|
|
4 |
from datetime import datetime
|
5 |
import logging
|
6 |
from typing import Dict, List, Optional
|
7 |
-
from pathlib import Path
|
8 |
-
import json
|
9 |
-
import dotenv
|
10 |
-
|
11 |
-
# Carrega variáveis de ambiente
|
12 |
-
dotenv.load_dotenv()
|
13 |
|
14 |
# Configuração do logging
|
15 |
-
logging.basicConfig(
|
16 |
-
level=logging.INFO,
|
17 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
18 |
-
handlers=[
|
19 |
-
logging.FileHandler("app.log"),
|
20 |
-
logging.StreamHandler()
|
21 |
-
]
|
22 |
-
)
|
23 |
logger = logging.getLogger(__name__)
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
# Tenta carregar do ambiente
|
28 |
-
token = os.getenv('HF_TOKEN')
|
29 |
-
if token:
|
30 |
-
return token
|
31 |
-
|
32 |
-
# Tenta carregar do arquivo de configuração
|
33 |
-
config_file = Path('config.json')
|
34 |
-
if config_file.exists():
|
35 |
-
try:
|
36 |
-
with open(config_file, 'r') as f:
|
37 |
-
config = json.load(f)
|
38 |
-
if token := config.get('hf_token'):
|
39 |
-
return token
|
40 |
-
except Exception as e:
|
41 |
-
logger.error(f"Erro ao ler config.json: {e}")
|
42 |
-
|
43 |
-
return ''
|
44 |
|
45 |
class DocumentGenerator:
|
46 |
"""Gerencia a geração de documentos usando HF Inference API"""
|
47 |
|
48 |
-
def __init__(self
|
49 |
-
|
50 |
-
raise ValueError("Token HF não configurado!")
|
51 |
-
|
52 |
-
self.client = InferenceClient(api_key=api_key)
|
53 |
self.model = "mistralai/Mistral-7B-Instruct-v0.2"
|
54 |
|
55 |
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
|
56 |
"""Gera o documento usando o modelo"""
|
57 |
try:
|
58 |
-
# Prepara as mensagens
|
59 |
messages = [
|
60 |
{
|
61 |
"role": "system",
|
62 |
-
"content": """Você é um advogado criminalista brasileiro
|
63 |
-
|
64 |
-
tecnicamente precisos e no formato do direito brasileiro."""
|
65 |
},
|
66 |
{
|
67 |
"role": "user",
|
68 |
-
"content": f"""Gere um {doc_type} completo
|
69 |
|
70 |
QUALIFICAÇÃO:
|
71 |
Cliente: {context.get('client_name')}
|
@@ -77,15 +42,7 @@ class DocumentGenerator:
|
|
77 |
{context.get('facts')}
|
78 |
|
79 |
FUNDAMENTOS JURÍDICOS:
|
80 |
-
{context.get('legal_basis')}
|
81 |
-
|
82 |
-
O documento deve seguir a formatação jurídica padrão brasileira, incluindo:
|
83 |
-
1. Cabeçalho com endereçamento correto
|
84 |
-
2. Qualificação completa das partes
|
85 |
-
3. Exposição clara dos fatos
|
86 |
-
4. Fundamentação jurídica sólida
|
87 |
-
5. Pedidos específicos
|
88 |
-
6. Fechamento formal com local, data e espaço para assinatura"""
|
89 |
}
|
90 |
]
|
91 |
|
@@ -95,7 +52,7 @@ class DocumentGenerator:
|
|
95 |
messages=messages,
|
96 |
temperature=0.3,
|
97 |
top_p=0.85,
|
98 |
-
max_tokens=2048
|
99 |
)
|
100 |
|
101 |
return self._format_output(completion.choices[0].message.content)
|
@@ -108,23 +65,13 @@ class DocumentGenerator:
|
|
108 |
"""Formata o texto gerado"""
|
109 |
if not text:
|
110 |
return "Erro: Nenhum texto gerado"
|
111 |
-
|
112 |
-
# Remove linhas vazias extras
|
113 |
-
lines = [line.strip() for line in text.split('\n') if line.strip()]
|
114 |
-
formatted_text = '\n\n'.join(lines)
|
115 |
-
|
116 |
-
return formatted_text.strip()
|
117 |
|
118 |
class WebInterface:
|
119 |
"""Interface Gradio para o gerador de documentos"""
|
120 |
|
121 |
def __init__(self):
|
122 |
-
|
123 |
-
token = load_token()
|
124 |
-
if not token:
|
125 |
-
raise ValueError("Token HF não encontrado!")
|
126 |
-
|
127 |
-
self.generator = DocumentGenerator(api_key=token)
|
128 |
self.create_interface()
|
129 |
|
130 |
def create_interface(self):
|
@@ -138,7 +85,7 @@ class WebInterface:
|
|
138 |
|
139 |
with gr.Row():
|
140 |
with gr.Column():
|
141 |
-
#
|
142 |
doc_type = gr.Dropdown(
|
143 |
choices=[
|
144 |
"Habeas Corpus",
|
@@ -149,76 +96,47 @@ class WebInterface:
|
|
149 |
"Apelação Criminal"
|
150 |
],
|
151 |
label="Tipo de Documento",
|
152 |
-
value="Habeas Corpus"
|
153 |
-
info="Selecione o tipo de peça processual"
|
154 |
)
|
155 |
|
156 |
-
#
|
157 |
with gr.Group():
|
158 |
gr.Markdown("### Informações do Processo")
|
159 |
-
|
160 |
client_name = gr.Textbox(
|
161 |
label="Nome do Cliente",
|
162 |
-
placeholder="Nome completo do cliente
|
163 |
-
info="Digite o nome completo"
|
164 |
)
|
165 |
-
|
166 |
process_number = gr.Textbox(
|
167 |
label="Número do Processo",
|
168 |
-
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN"
|
169 |
-
info="Número CNJ do processo"
|
170 |
)
|
171 |
-
|
172 |
court = gr.Textbox(
|
173 |
label="Tribunal",
|
174 |
-
value="TRIBUNAL DE JUSTIÇA DO ESTADO"
|
175 |
-
info="Nome completo do tribunal"
|
176 |
)
|
177 |
-
|
178 |
jurisdiction = gr.Textbox(
|
179 |
label="Comarca",
|
180 |
-
placeholder="Nome da comarca"
|
181 |
-
info="Comarca onde tramita o processo"
|
182 |
)
|
183 |
|
184 |
# Detalhes do caso
|
185 |
with gr.Group():
|
186 |
gr.Markdown("### Detalhes do Caso")
|
187 |
-
|
188 |
facts = gr.Textbox(
|
189 |
label="Fatos",
|
190 |
lines=5,
|
191 |
-
placeholder="Descreva os fatos relevantes
|
192 |
-
info="Descreva os fatos de forma clara e objetiva"
|
193 |
)
|
194 |
-
|
195 |
legal_basis = gr.Textbox(
|
196 |
label="Fundamentos Jurídicos",
|
197 |
lines=3,
|
198 |
-
placeholder="
|
199 |
-
info="Artigos, jurisprudência e doutrina aplicáveis"
|
200 |
)
|
201 |
|
202 |
-
# Botões
|
203 |
with gr.Row():
|
204 |
-
generate_btn = gr.Button(
|
205 |
-
|
206 |
-
variant="primary",
|
207 |
-
scale=2
|
208 |
-
)
|
209 |
-
|
210 |
-
clear_btn = gr.Button(
|
211 |
-
"🗑️ Limpar Campos",
|
212 |
-
variant="secondary",
|
213 |
-
scale=1
|
214 |
-
)
|
215 |
-
|
216 |
-
status = gr.Textbox(
|
217 |
-
label="Status",
|
218 |
-
interactive=False
|
219 |
-
)
|
220 |
|
221 |
-
# Coluna do documento gerado
|
222 |
with gr.Column():
|
223 |
output = gr.Textbox(
|
224 |
label="Documento Gerado",
|
@@ -226,9 +144,7 @@ class WebInterface:
|
|
226 |
show_copy_button=True
|
227 |
)
|
228 |
|
229 |
-
|
230 |
-
save_btn = gr.Button("💾 Salvar como TXT")
|
231 |
-
copy_btn = gr.Button("📋 Copiar")
|
232 |
|
233 |
# Exemplos de uso
|
234 |
gr.Examples(
|
@@ -288,29 +204,6 @@ class WebInterface:
|
|
288 |
jurisdiction, facts, legal_basis, status
|
289 |
]
|
290 |
)
|
291 |
-
|
292 |
-
def save_to_file(text):
|
293 |
-
if not text:
|
294 |
-
return "Nenhum documento para salvar"
|
295 |
-
filename = f"documento_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
296 |
-
try:
|
297 |
-
with open(filename, 'w', encoding='utf-8') as f:
|
298 |
-
f.write(text)
|
299 |
-
return f"✅ Documento salvo como {filename}"
|
300 |
-
except Exception as e:
|
301 |
-
return f"❌ Erro ao salvar: {str(e)}"
|
302 |
-
|
303 |
-
save_btn.click(
|
304 |
-
fn=save_to_file,
|
305 |
-
inputs=[output],
|
306 |
-
outputs=[status]
|
307 |
-
)
|
308 |
-
|
309 |
-
copy_btn.click(
|
310 |
-
fn=lambda x: x,
|
311 |
-
inputs=[output],
|
312 |
-
outputs=[output]
|
313 |
-
)
|
314 |
|
315 |
def _generate_document(
|
316 |
self, doc_type: str, client_name: str,
|
@@ -319,7 +212,6 @@ class WebInterface:
|
|
319 |
legal_basis: str
|
320 |
) -> tuple:
|
321 |
"""Gera o documento com os parâmetros fornecidos"""
|
322 |
-
|
323 |
try:
|
324 |
# Validação
|
325 |
if not all([client_name, process_number, facts, legal_basis]):
|
@@ -334,9 +226,6 @@ class WebInterface:
|
|
334 |
"legal_basis": legal_basis
|
335 |
}
|
336 |
|
337 |
-
# Atualiza status
|
338 |
-
yield "", "⏳ Gerando documento..."
|
339 |
-
|
340 |
# Gera documento
|
341 |
result = self.generator.generate(doc_type, context)
|
342 |
|
@@ -348,21 +237,8 @@ class WebInterface:
|
|
348 |
|
349 |
def launch(self):
|
350 |
"""Inicia a interface web"""
|
351 |
-
self.app.launch(
|
352 |
|
353 |
if __name__ == "__main__":
|
354 |
-
# Verifica se o token está configurado
|
355 |
-
if not HF_API_TOKEN:
|
356 |
-
print("\n⚠️ Token HF não encontrado!")
|
357 |
-
print("\nPara configurar o token:")
|
358 |
-
print("1. Crie um arquivo .env com:")
|
359 |
-
print(" HF_TOKEN=seu_token_aqui")
|
360 |
-
print("\nOu")
|
361 |
-
print("2. Crie um arquivo config.json com:")
|
362 |
-
print(' {"hf_token": "seu_token_aqui"}')
|
363 |
-
print("\nOu")
|
364 |
-
print("3. Configure a variável de ambiente HF_TOKEN")
|
365 |
-
exit(1)
|
366 |
-
|
367 |
interface = WebInterface()
|
368 |
interface.launch()
|
|
|
4 |
from datetime import datetime
|
5 |
import logging
|
6 |
from typing import Dict, List, Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Configuração do logging
|
9 |
+
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
logger = logging.getLogger(__name__)
|
11 |
|
12 |
+
# Token já definido no ambiente HF Spaces
|
13 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
class DocumentGenerator:
|
16 |
"""Gerencia a geração de documentos usando HF Inference API"""
|
17 |
|
18 |
+
def __init__(self):
|
19 |
+
self.client = InferenceClient(api_key=HF_TOKEN)
|
|
|
|
|
|
|
20 |
self.model = "mistralai/Mistral-7B-Instruct-v0.2"
|
21 |
|
22 |
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
|
23 |
"""Gera o documento usando o modelo"""
|
24 |
try:
|
|
|
25 |
messages = [
|
26 |
{
|
27 |
"role": "system",
|
28 |
+
"content": """Você é um advogado criminalista brasileiro experiente.
|
29 |
+
Gere documentos jurídicos formais no formato do direito brasileiro."""
|
|
|
30 |
},
|
31 |
{
|
32 |
"role": "user",
|
33 |
+
"content": f"""Gere um {doc_type} completo e tecnicamente preciso com:
|
34 |
|
35 |
QUALIFICAÇÃO:
|
36 |
Cliente: {context.get('client_name')}
|
|
|
42 |
{context.get('facts')}
|
43 |
|
44 |
FUNDAMENTOS JURÍDICOS:
|
45 |
+
{context.get('legal_basis')}"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
}
|
47 |
]
|
48 |
|
|
|
52 |
messages=messages,
|
53 |
temperature=0.3,
|
54 |
top_p=0.85,
|
55 |
+
max_tokens=2048
|
56 |
)
|
57 |
|
58 |
return self._format_output(completion.choices[0].message.content)
|
|
|
65 |
"""Formata o texto gerado"""
|
66 |
if not text:
|
67 |
return "Erro: Nenhum texto gerado"
|
68 |
+
return text.strip()
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
class WebInterface:
|
71 |
"""Interface Gradio para o gerador de documentos"""
|
72 |
|
73 |
def __init__(self):
|
74 |
+
self.generator = DocumentGenerator()
|
|
|
|
|
|
|
|
|
|
|
75 |
self.create_interface()
|
76 |
|
77 |
def create_interface(self):
|
|
|
85 |
|
86 |
with gr.Row():
|
87 |
with gr.Column():
|
88 |
+
# Seleção do tipo de documento
|
89 |
doc_type = gr.Dropdown(
|
90 |
choices=[
|
91 |
"Habeas Corpus",
|
|
|
96 |
"Apelação Criminal"
|
97 |
],
|
98 |
label="Tipo de Documento",
|
99 |
+
value="Habeas Corpus"
|
|
|
100 |
)
|
101 |
|
102 |
+
# Dados do processo
|
103 |
with gr.Group():
|
104 |
gr.Markdown("### Informações do Processo")
|
|
|
105 |
client_name = gr.Textbox(
|
106 |
label="Nome do Cliente",
|
107 |
+
placeholder="Nome completo do cliente"
|
|
|
108 |
)
|
|
|
109 |
process_number = gr.Textbox(
|
110 |
label="Número do Processo",
|
111 |
+
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN"
|
|
|
112 |
)
|
|
|
113 |
court = gr.Textbox(
|
114 |
label="Tribunal",
|
115 |
+
value="TRIBUNAL DE JUSTIÇA DO ESTADO"
|
|
|
116 |
)
|
|
|
117 |
jurisdiction = gr.Textbox(
|
118 |
label="Comarca",
|
119 |
+
placeholder="Nome da comarca"
|
|
|
120 |
)
|
121 |
|
122 |
# Detalhes do caso
|
123 |
with gr.Group():
|
124 |
gr.Markdown("### Detalhes do Caso")
|
|
|
125 |
facts = gr.Textbox(
|
126 |
label="Fatos",
|
127 |
lines=5,
|
128 |
+
placeholder="Descreva os fatos relevantes..."
|
|
|
129 |
)
|
|
|
130 |
legal_basis = gr.Textbox(
|
131 |
label="Fundamentos Jurídicos",
|
132 |
lines=3,
|
133 |
+
placeholder="Indique os fundamentos legais..."
|
|
|
134 |
)
|
135 |
|
|
|
136 |
with gr.Row():
|
137 |
+
generate_btn = gr.Button("Gerar Documento", variant="primary")
|
138 |
+
clear_btn = gr.Button("Limpar", variant="secondary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
|
|
|
140 |
with gr.Column():
|
141 |
output = gr.Textbox(
|
142 |
label="Documento Gerado",
|
|
|
144 |
show_copy_button=True
|
145 |
)
|
146 |
|
147 |
+
status = gr.Textbox(label="Status")
|
|
|
|
|
148 |
|
149 |
# Exemplos de uso
|
150 |
gr.Examples(
|
|
|
204 |
jurisdiction, facts, legal_basis, status
|
205 |
]
|
206 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
207 |
|
208 |
def _generate_document(
|
209 |
self, doc_type: str, client_name: str,
|
|
|
212 |
legal_basis: str
|
213 |
) -> tuple:
|
214 |
"""Gera o documento com os parâmetros fornecidos"""
|
|
|
215 |
try:
|
216 |
# Validação
|
217 |
if not all([client_name, process_number, facts, legal_basis]):
|
|
|
226 |
"legal_basis": legal_basis
|
227 |
}
|
228 |
|
|
|
|
|
|
|
229 |
# Gera documento
|
230 |
result = self.generator.generate(doc_type, context)
|
231 |
|
|
|
237 |
|
238 |
def launch(self):
|
239 |
"""Inicia a interface web"""
|
240 |
+
self.app.launch()
|
241 |
|
242 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
243 |
interface = WebInterface()
|
244 |
interface.launch()
|