Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,320 +1,264 @@
|
|
1 |
import gradio as gr
|
2 |
from gradio_client import Client
|
3 |
import json
|
4 |
-
import sqlite3
|
5 |
from datetime import datetime
|
6 |
import os
|
7 |
from typing import Dict, List, Optional
|
8 |
-
import asyncio
|
9 |
-
from pathlib import Path
|
10 |
import logging
|
11 |
|
12 |
-
logging
|
|
|
|
|
|
|
|
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
15 |
-
class
|
16 |
-
|
17 |
-
self.db_path = db_path
|
18 |
-
self.init_database()
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
CREATE TABLE IF NOT EXISTS documents (
|
24 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
25 |
-
title TEXT,
|
26 |
-
doc_type TEXT,
|
27 |
-
content TEXT,
|
28 |
-
created_at TIMESTAMP,
|
29 |
-
client_name TEXT,
|
30 |
-
process_number TEXT,
|
31 |
-
template_used TEXT
|
32 |
-
)
|
33 |
-
""")
|
34 |
-
conn.execute("""
|
35 |
-
CREATE TABLE IF NOT EXISTS templates (
|
36 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
37 |
-
name TEXT,
|
38 |
-
doc_type TEXT,
|
39 |
-
content TEXT,
|
40 |
-
created_at TIMESTAMP
|
41 |
-
)
|
42 |
-
""")
|
43 |
-
conn.execute("""
|
44 |
-
CREATE TABLE IF NOT EXISTS jurisprudence (
|
45 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
46 |
-
topic TEXT,
|
47 |
-
content TEXT,
|
48 |
-
source TEXT,
|
49 |
-
relevance INTEGER
|
50 |
-
)
|
51 |
-
""")
|
52 |
-
|
53 |
-
class PromptOptimizer:
|
54 |
-
def __init__(self):
|
55 |
-
self.base_prompts = self._load_base_prompts()
|
56 |
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
|
63 |
-
{
|
64 |
|
65 |
-
|
66 |
-
|
67 |
-
2. Cite jurisprudência relevante dos tribunais superiores
|
68 |
-
3. Estruture o documento com todas as partes necessárias
|
69 |
-
4. Inclua argumentos constitucionais pertinentes
|
70 |
-
5. Faça referências específicas ao CPP
|
71 |
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
78 |
""",
|
79 |
|
80 |
-
"
|
81 |
-
Atue como um
|
82 |
|
83 |
-
|
84 |
-
{
|
|
|
|
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
2. Tipifique corretamente a conduta
|
89 |
-
3. Indique as circunstâncias do crime
|
90 |
-
4. Qualifique todos os envolvidos
|
91 |
-
5. Indique as provas disponíveis
|
92 |
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
99 |
""",
|
100 |
|
101 |
-
"
|
102 |
-
Atue como um advogado criminalista e gere
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
-
|
105 |
-
{
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
2. Indique violação à lei federal
|
110 |
-
3. Cite precedentes do STJ
|
111 |
-
4. Demonstre divergência jurisprudencial
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
118 |
"""
|
119 |
}
|
120 |
-
|
121 |
-
|
122 |
-
base_prompt = self.base_prompts.get(doc_type, "")
|
123 |
-
optimized = base_prompt.format(caso_detalhes=json.dumps(context, indent=2))
|
124 |
-
return optimized
|
125 |
|
126 |
-
class
|
|
|
|
|
127 |
def __init__(self):
|
128 |
self.client = Client("ysharma/Chat_with_Meta_llama3_8b")
|
129 |
-
self.
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
template_id: Optional[int] = None) -> str:
|
134 |
try:
|
135 |
-
|
136 |
-
optimized_prompt = self.prompt_optimizer.optimize_prompt(doc_type, context)
|
137 |
-
|
138 |
-
# Gera o documento usando a API do Llama
|
139 |
-
result = await self._generate_with_llama(optimized_prompt)
|
140 |
|
141 |
-
|
142 |
-
|
|
|
|
|
|
|
|
|
143 |
|
144 |
-
return result
|
145 |
|
146 |
except Exception as e:
|
147 |
logger.error(f"Erro na geração do documento: {str(e)}")
|
148 |
-
|
149 |
-
|
150 |
-
async def _generate_with_llama(self, prompt: str) -> str:
|
151 |
-
return self.client.predict(
|
152 |
-
message=prompt,
|
153 |
-
request=0.85, # Temperatura reduzida para maior consistência
|
154 |
-
param_3=3072, # Aumentado para documentos mais longos
|
155 |
-
api_name="/chat"
|
156 |
-
)
|
157 |
|
158 |
-
def
|
159 |
-
|
160 |
-
|
161 |
-
INSERT INTO documents
|
162 |
-
(title, doc_type, content, created_at, client_name, process_number)
|
163 |
-
VALUES (?, ?, ?, ?, ?, ?)
|
164 |
-
""", (
|
165 |
-
f"{doc_type}_{context.get('client_name')}",
|
166 |
-
doc_type,
|
167 |
-
content,
|
168 |
-
datetime.now(),
|
169 |
-
context.get('client_name'),
|
170 |
-
context.get('process_number')
|
171 |
-
))
|
172 |
|
173 |
-
class
|
|
|
|
|
174 |
def __init__(self):
|
175 |
-
self.generator =
|
176 |
self.create_interface()
|
177 |
|
178 |
def create_interface(self):
|
179 |
-
|
|
|
|
|
180 |
gr.Markdown("""
|
181 |
-
#
|
182 |
### Powered by LLM Technology
|
183 |
""")
|
184 |
|
185 |
-
with gr.
|
186 |
-
with gr.
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
lines=30,
|
240 |
-
show_copy_button=True
|
241 |
-
)
|
242 |
-
|
243 |
-
with gr.Row():
|
244 |
-
save_btn = gr.Button("Salvar Documento")
|
245 |
-
export_btn = gr.Button("Exportar como PDF")
|
246 |
-
|
247 |
-
with gr.Tab("Gerenciar Templates"):
|
248 |
-
self._create_template_manager()
|
249 |
|
250 |
-
with gr.
|
251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
252 |
|
253 |
# Eventos
|
254 |
generate_btn.click(
|
255 |
fn=self._generate_document,
|
256 |
inputs=[
|
257 |
-
doc_type, client_name, process_number,
|
258 |
-
jurisdiction, facts, legal_basis
|
259 |
-
template_select, include_jurisprudence
|
260 |
],
|
261 |
outputs=output
|
262 |
)
|
263 |
-
|
264 |
-
use_template.change(
|
265 |
-
fn=lambda x: gr.update(visible=x),
|
266 |
-
inputs=[use_template],
|
267 |
-
outputs=[template_select]
|
268 |
-
)
|
269 |
-
|
270 |
-
def _get_templates(self) -> List[str]:
|
271 |
-
with sqlite3.connect(self.generator.db.db_path) as conn:
|
272 |
-
templates = conn.execute("SELECT name FROM templates").fetchall()
|
273 |
-
return [t[0] for t in templates]
|
274 |
-
|
275 |
-
def _create_template_manager(self):
|
276 |
-
with gr.Group():
|
277 |
-
gr.Markdown("### Gerenciar Templates")
|
278 |
-
template_name = gr.Textbox(label="Nome do Template")
|
279 |
-
template_content = gr.Textbox(label="Conteúdo", lines=10)
|
280 |
-
save_template_btn = gr.Button("Salvar Template")
|
281 |
-
|
282 |
-
def _create_history_viewer(self):
|
283 |
-
with gr.Group():
|
284 |
-
gr.Markdown("### Histórico de Documentos")
|
285 |
-
history_table = gr.Dataframe(
|
286 |
-
headers=["Data", "Tipo", "Cliente", "Processo"],
|
287 |
-
row_count=10
|
288 |
-
)
|
289 |
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
"facts": args[5],
|
298 |
-
"legal_basis": args[6],
|
299 |
-
"use_template": args[7],
|
300 |
-
"template": args[8] if args[7] else None,
|
301 |
-
"include_jurisprudence": args[9]
|
302 |
-
}
|
303 |
-
|
304 |
-
result = await self.generator.generate_document(
|
305 |
-
doc_type=args[0].lower().replace(" ", "_"),
|
306 |
-
context=context
|
307 |
-
)
|
308 |
-
|
309 |
-
return result
|
310 |
|
311 |
-
|
312 |
-
|
313 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
314 |
|
315 |
def launch(self):
|
|
|
316 |
self.app.launch(share=True)
|
317 |
|
318 |
if __name__ == "__main__":
|
319 |
-
interface =
|
320 |
interface.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from gradio_client import Client
|
3 |
import json
|
|
|
4 |
from datetime import datetime
|
5 |
import os
|
6 |
from typing import Dict, List, Optional
|
|
|
|
|
7 |
import logging
|
8 |
|
9 |
+
# Configuração do logging
|
10 |
+
logging.basicConfig(
|
11 |
+
level=logging.INFO,
|
12 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
13 |
+
)
|
14 |
logger = logging.getLogger(__name__)
|
15 |
|
16 |
+
class PromptManager:
|
17 |
+
"""Gerencia a criação e otimização de prompts"""
|
|
|
|
|
18 |
|
19 |
+
@staticmethod
|
20 |
+
def get_base_prompt(doc_type: str, context: Dict[str, str]) -> str:
|
21 |
+
"""Retorna o prompt base para cada tipo de documento"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
prompts = {
|
24 |
+
"habeas_corpus": f"""
|
25 |
+
Atue como um advogado criminalista experiente e gere um Habeas Corpus detalhado:
|
26 |
+
|
27 |
+
DADOS DO CASO:
|
28 |
+
Cliente: {context.get('client_name')}
|
29 |
+
Processo: {context.get('process_number')}
|
30 |
+
Tribunal: {context.get('court')}
|
31 |
+
Comarca: {context.get('jurisdiction')}
|
32 |
|
33 |
+
FATOS:
|
34 |
+
{context.get('facts')}
|
35 |
|
36 |
+
FUNDAMENTOS JURÍDICOS:
|
37 |
+
{context.get('legal_basis')}
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
Gere um Habeas Corpus completo e tecnicamente preciso, incluindo:
|
40 |
+
1. Cabeçalho com endereçamento correto
|
41 |
+
2. Qualificação das partes
|
42 |
+
3. Fatos relevantes
|
43 |
+
4. Fundamentos jurídicos
|
44 |
+
5. Jurisprudência relevante
|
45 |
+
6. Pedidos (liminar e mérito)
|
46 |
""",
|
47 |
|
48 |
+
"denuncia": f"""
|
49 |
+
Atue como um promotor de justiça experiente e gere uma denúncia criminal:
|
50 |
|
51 |
+
DADOS DO CASO:
|
52 |
+
Processo: {context.get('process_number')}
|
53 |
+
Tribunal: {context.get('court')}
|
54 |
+
Comarca: {context.get('jurisdiction')}
|
55 |
|
56 |
+
FATOS:
|
57 |
+
{context.get('facts')}
|
|
|
|
|
|
|
|
|
58 |
|
59 |
+
ENQUADRAMENTO LEGAL:
|
60 |
+
{context.get('legal_basis')}
|
61 |
+
|
62 |
+
Gere uma denúncia criminal completa, incluindo:
|
63 |
+
1. Qualificação do(s) denunciado(s)
|
64 |
+
2. Narrativa clara dos fatos
|
65 |
+
3. Tipificação penal
|
66 |
+
4. Circunstâncias do crime
|
67 |
+
5. Rol de testemunhas
|
68 |
+
6. Pedidos
|
69 |
""",
|
70 |
|
71 |
+
"alegacoes_finais": f"""
|
72 |
+
Atue como um advogado criminalista e gere alegações finais:
|
73 |
+
|
74 |
+
DADOS DO PROCESSO:
|
75 |
+
Cliente: {context.get('client_name')}
|
76 |
+
Processo: {context.get('process_number')}
|
77 |
+
Tribunal: {context.get('court')}
|
78 |
|
79 |
+
FATOS E PROVAS:
|
80 |
+
{context.get('facts')}
|
81 |
|
82 |
+
TESE DEFENSIVA:
|
83 |
+
{context.get('legal_basis')}
|
|
|
|
|
|
|
84 |
|
85 |
+
Elabore alegações finais completas, incluindo:
|
86 |
+
1. Relatório do processo
|
87 |
+
2. Preliminares (se houver)
|
88 |
+
3. Mérito
|
89 |
+
4. Análise das provas
|
90 |
+
5. Pedidos
|
91 |
"""
|
92 |
}
|
93 |
+
|
94 |
+
return prompts.get(doc_type, "Tipo de documento não suportado")
|
|
|
|
|
|
|
95 |
|
96 |
+
class DocumentGenerator:
|
97 |
+
"""Gerencia a geração de documentos usando a API do LLama"""
|
98 |
+
|
99 |
def __init__(self):
|
100 |
self.client = Client("ysharma/Chat_with_Meta_llama3_8b")
|
101 |
+
self.prompt_manager = PromptManager()
|
102 |
+
|
103 |
+
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
|
104 |
+
"""Gera o documento baseado no tipo e contexto"""
|
|
|
105 |
try:
|
106 |
+
prompt = self.prompt_manager.get_base_prompt(doc_type, context)
|
|
|
|
|
|
|
|
|
107 |
|
108 |
+
result = self.client.predict(
|
109 |
+
message=prompt,
|
110 |
+
request=0.85, # temperatura mais baixa para maior consistência
|
111 |
+
param_3=3072, # tokens aumentados para documentos longos
|
112 |
+
api_name="/chat"
|
113 |
+
)
|
114 |
|
115 |
+
return self._format_output(result)
|
116 |
|
117 |
except Exception as e:
|
118 |
logger.error(f"Erro na geração do documento: {str(e)}")
|
119 |
+
return f"Erro na geração do documento: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
def _format_output(self, text: str) -> str:
|
122 |
+
"""Formata o texto gerado para melhor apresentação"""
|
123 |
+
return text.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
|
125 |
+
class WebInterface:
|
126 |
+
"""Interface Gradio para o gerador de documentos"""
|
127 |
+
|
128 |
def __init__(self):
|
129 |
+
self.generator = DocumentGenerator()
|
130 |
self.create_interface()
|
131 |
|
132 |
def create_interface(self):
|
133 |
+
"""Cria a interface web com Gradio"""
|
134 |
+
|
135 |
+
with gr.Blocks(theme=gr.themes.Soft()) as self.app:
|
136 |
gr.Markdown("""
|
137 |
+
# Gerador de Documentos Criminais
|
138 |
### Powered by LLM Technology
|
139 |
""")
|
140 |
|
141 |
+
with gr.Row():
|
142 |
+
with gr.Column():
|
143 |
+
# Seleção do tipo de documento
|
144 |
+
doc_type = gr.Dropdown(
|
145 |
+
choices=[
|
146 |
+
"Habeas Corpus",
|
147 |
+
"Denúncia",
|
148 |
+
"Alegações Finais",
|
149 |
+
"Resposta à Acusação",
|
150 |
+
"Recurso em Sentido Estrito",
|
151 |
+
"Apelação Criminal"
|
152 |
+
],
|
153 |
+
label="Tipo de Documento",
|
154 |
+
value="Habeas Corpus"
|
155 |
+
)
|
156 |
+
|
157 |
+
# Informações do processo
|
158 |
+
with gr.Group():
|
159 |
+
gr.Markdown("### Informações do Processo")
|
160 |
+
client_name = gr.Textbox(
|
161 |
+
label="Nome do Cliente",
|
162 |
+
placeholder="Nome completo do cliente"
|
163 |
+
)
|
164 |
+
process_number = gr.Textbox(
|
165 |
+
label="Número do Processo",
|
166 |
+
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN"
|
167 |
+
)
|
168 |
+
court = gr.Textbox(
|
169 |
+
label="Tribunal",
|
170 |
+
value="TRIBUNAL DE JUSTIÇA DO ESTADO"
|
171 |
+
)
|
172 |
+
jurisdiction = gr.Textbox(
|
173 |
+
label="Comarca",
|
174 |
+
placeholder="Comarca onde tramita o processo"
|
175 |
+
)
|
176 |
+
|
177 |
+
# Detalhes do caso
|
178 |
+
with gr.Group():
|
179 |
+
gr.Markdown("### Detalhes do Caso")
|
180 |
+
facts = gr.Textbox(
|
181 |
+
label="Fatos",
|
182 |
+
lines=5,
|
183 |
+
placeholder="Descreva os fatos relevantes do caso..."
|
184 |
+
)
|
185 |
+
legal_basis = gr.Textbox(
|
186 |
+
label="Fundamentos Jurídicos",
|
187 |
+
lines=3,
|
188 |
+
placeholder="Indique os fundamentos legais principais..."
|
189 |
+
)
|
190 |
+
|
191 |
+
generate_btn = gr.Button(
|
192 |
+
"Gerar Documento",
|
193 |
+
variant="primary"
|
194 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
|
196 |
+
with gr.Column():
|
197 |
+
output = gr.Textbox(
|
198 |
+
label="Documento Gerado",
|
199 |
+
lines=30,
|
200 |
+
show_copy_button=True
|
201 |
+
)
|
202 |
+
|
203 |
+
# Exemplos de uso
|
204 |
+
gr.Examples(
|
205 |
+
examples=[
|
206 |
+
[
|
207 |
+
"Habeas Corpus",
|
208 |
+
"João da Silva",
|
209 |
+
"0000123-45.2024.8.26.0000",
|
210 |
+
"TRIBUNAL DE JUSTIÇA DO ESTADO DE SÃO PAULO",
|
211 |
+
"São Paulo",
|
212 |
+
"Paciente preso em flagrante no dia 25/12/2024 por suposto furto...",
|
213 |
+
"Art. 5º, LXVIII da CF/88; Art. 647 do CPP; Ausência dos requisitos do Art. 312 do CPP"
|
214 |
+
]
|
215 |
+
],
|
216 |
+
inputs=[
|
217 |
+
doc_type, client_name, process_number,
|
218 |
+
court, jurisdiction, facts, legal_basis
|
219 |
+
]
|
220 |
+
)
|
221 |
|
222 |
# Eventos
|
223 |
generate_btn.click(
|
224 |
fn=self._generate_document,
|
225 |
inputs=[
|
226 |
+
doc_type, client_name, process_number,
|
227 |
+
court, jurisdiction, facts, legal_basis
|
|
|
228 |
],
|
229 |
outputs=output
|
230 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
231 |
|
232 |
+
def _generate_document(
|
233 |
+
self, doc_type: str, client_name: str,
|
234 |
+
process_number: str, court: str,
|
235 |
+
jurisdiction: str, facts: str,
|
236 |
+
legal_basis: str
|
237 |
+
) -> str:
|
238 |
+
"""Gera o documento com os parâmetros fornecidos"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
239 |
|
240 |
+
# Validação básica
|
241 |
+
if not all([client_name, process_number, facts, legal_basis]):
|
242 |
+
return "Erro: Todos os campos obrigatórios devem ser preenchidos"
|
243 |
+
|
244 |
+
context = {
|
245 |
+
"client_name": client_name,
|
246 |
+
"process_number": process_number,
|
247 |
+
"court": court,
|
248 |
+
"jurisdiction": jurisdiction,
|
249 |
+
"facts": facts,
|
250 |
+
"legal_basis": legal_basis
|
251 |
+
}
|
252 |
+
|
253 |
+
return self.generator.generate(
|
254 |
+
doc_type.lower().replace(" ", "_"),
|
255 |
+
context
|
256 |
+
)
|
257 |
|
258 |
def launch(self):
|
259 |
+
"""Inicia a interface web"""
|
260 |
self.app.launch(share=True)
|
261 |
|
262 |
if __name__ == "__main__":
|
263 |
+
interface = WebInterface()
|
264 |
interface.launch()
|