DHEIVER commited on
Commit
716ba45
·
verified ·
1 Parent(s): 8352d09

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +320 -0
app.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class DatabaseManager:
16
+ def __init__(self, db_path: str = "legal_docs.db"):
17
+ self.db_path = db_path
18
+ self.init_database()
19
+
20
+ def init_database(self):
21
+ with sqlite3.connect(self.db_path) as conn:
22
+ conn.execute("""
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
+ def _load_base_prompts(self) -> Dict[str, str]:
58
+ return {
59
+ "habeas_corpus": """
60
+ Atue como um advogado criminalista experiente e gere um Habeas Corpus detalhado e tecnicamente preciso:
61
+
62
+ CONTEXTO DO CASO:
63
+ {caso_detalhes}
64
+
65
+ REQUISITOS ESPECÍFICOS:
66
+ 1. Use linguagem jurídica formal
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
+ ESTRUTURA REQUERIDA:
73
+ - Cabeçalho completo com qualificação
74
+ - Fatos detalhados
75
+ - Fundamentos jurídicos
76
+ - Jurisprudência aplicável
77
+ - Pedidos liminar e final
78
+ """,
79
+
80
+ "denuncia_crime": """
81
+ Atue como um advogado criminalista experiente e gere uma denúncia criminal detalhada:
82
+
83
+ DETALHES DO CASO:
84
+ {caso_detalhes}
85
+
86
+ REQUISITOS:
87
+ 1. Descreva os fatos com precisão temporal
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
+ ESTRUTURA:
94
+ - Qualificação completa
95
+ - Narrativa dos fatos
96
+ - Tipificação penal
97
+ - Pedidos
98
+ - Provas a produzir
99
+ """,
100
+
101
+ "recurso_especial": """
102
+ Atue como um advogado criminalista e gere um Recurso Especial Criminal:
103
+
104
+ CASO E DECISÃO RECORRIDA:
105
+ {caso_detalhes}
106
+
107
+ REQUISITOS:
108
+ 1. Demonstre o prequestionamento
109
+ 2. Indique violação à lei federal
110
+ 3. Cite precedentes do STJ
111
+ 4. Demonstre divergência jurisprudencial
112
+
113
+ ESTRUTURA:
114
+ - Cabimento e tempestividade
115
+ - Prequestionamento
116
+ - Mérito recursal
117
+ - Pedidos
118
+ """
119
+ }
120
+
121
+ def optimize_prompt(self, doc_type: str, context: Dict[str, str]) -> str:
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 LegalDocumentGenerator:
127
+ def __init__(self):
128
+ self.client = Client("ysharma/Chat_with_Meta_llama3_8b")
129
+ self.db = DatabaseManager()
130
+ self.prompt_optimizer = PromptOptimizer()
131
+
132
+ async def generate_document(self, doc_type: str, context: Dict[str, str],
133
+ template_id: Optional[int] = None) -> str:
134
+ try:
135
+ # Otimiza o prompt baseado no tipo de documento
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
+ # Salva o documento gerado
142
+ self._save_document(doc_type, result, context)
143
+
144
+ return result
145
+
146
+ except Exception as e:
147
+ logger.error(f"Erro na geração do documento: {str(e)}")
148
+ raise
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 _save_document(self, doc_type: str, content: str, context: Dict[str, str]):
159
+ with sqlite3.connect(self.db.db_path) as conn:
160
+ conn.execute("""
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 AdvancedLegalInterface:
174
+ def __init__(self):
175
+ self.generator = LegalDocumentGenerator()
176
+ self.create_interface()
177
+
178
+ def create_interface(self):
179
+ with gr.Blocks(theme=gr.themes.Glass()) as self.app:
180
+ gr.Markdown("""
181
+ # Sistema Avançado de Geração de Peças Criminais
182
+ ### Powered by LLM Technology
183
+ """)
184
+
185
+ with gr.Tabs():
186
+ with gr.Tab("Gerar Documento"):
187
+ with gr.Row():
188
+ with gr.Column():
189
+ doc_type = gr.Dropdown(
190
+ choices=[
191
+ "Habeas Corpus",
192
+ "Denúncia Criminal",
193
+ "Recurso Especial",
194
+ "Alegações Finais",
195
+ "Resposta à Acusação",
196
+ "Revisão Criminal",
197
+ "Apelação Criminal"
198
+ ],
199
+ label="Tipo de Documento"
200
+ )
201
+
202
+ client_info = gr.Group()
203
+ with client_info:
204
+ client_name = gr.Textbox(label="Nome do Cliente")
205
+ process_number = gr.Textbox(label="Número do Processo")
206
+ court = gr.Textbox(label="Tribunal")
207
+ jurisdiction = gr.Textbox(label="Comarca")
208
+
209
+ case_details = gr.Group()
210
+ with case_details:
211
+ facts = gr.Textbox(
212
+ label="Fatos",
213
+ lines=5,
214
+ placeholder="Descreva os fatos relevantes..."
215
+ )
216
+ legal_basis = gr.Textbox(
217
+ label="Fundamentos Jurídicos",
218
+ lines=3,
219
+ placeholder="Indique os principais fundamentos legais..."
220
+ )
221
+
222
+ advanced_options = gr.Group()
223
+ with advanced_options:
224
+ use_template = gr.Checkbox(label="Usar Template Personalizado")
225
+ template_select = gr.Dropdown(
226
+ choices=self._get_templates(),
227
+ label="Template",
228
+ visible=False
229
+ )
230
+ include_jurisprudence = gr.Checkbox(
231
+ label="Incluir Jurisprudência Relevante"
232
+ )
233
+
234
+ generate_btn = gr.Button("Gerar Documento", variant="primary")
235
+
236
+ with gr.Column():
237
+ output = gr.Textbox(
238
+ label="Documento Gerado",
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.Tab("Histórico"):
251
+ self._create_history_viewer()
252
+
253
+ # Eventos
254
+ generate_btn.click(
255
+ fn=self._generate_document,
256
+ inputs=[
257
+ doc_type, client_name, process_number, court,
258
+ jurisdiction, facts, legal_basis, use_template,
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
+ async def _generate_document(self, *args) -> str:
291
+ try:
292
+ context = {
293
+ "client_name": args[1],
294
+ "process_number": args[2],
295
+ "court": args[3],
296
+ "jurisdiction": args[4],
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
+ except Exception as e:
312
+ logger.error(f"Erro na geração: {str(e)}")
313
+ return f"Erro na geração do documento: {str(e)}"
314
+
315
+ def launch(self):
316
+ self.app.launch(share=True)
317
+
318
+ if __name__ == "__main__":
319
+ interface = AdvancedLegalInterface()
320
+ interface.launch()