Spaces:
Sleeping
Sleeping
File size: 12,360 Bytes
716ba45 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
import gradio as gr
from gradio_client import Client
import json
import sqlite3
from datetime import datetime
import os
from typing import Dict, List, Optional
import asyncio
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DatabaseManager:
def __init__(self, db_path: str = "legal_docs.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
doc_type TEXT,
content TEXT,
created_at TIMESTAMP,
client_name TEXT,
process_number TEXT,
template_used TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
doc_type TEXT,
content TEXT,
created_at TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS jurisprudence (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic TEXT,
content TEXT,
source TEXT,
relevance INTEGER
)
""")
class PromptOptimizer:
def __init__(self):
self.base_prompts = self._load_base_prompts()
def _load_base_prompts(self) -> Dict[str, str]:
return {
"habeas_corpus": """
Atue como um advogado criminalista experiente e gere um Habeas Corpus detalhado e tecnicamente preciso:
CONTEXTO DO CASO:
{caso_detalhes}
REQUISITOS ESPECÍFICOS:
1. Use linguagem jurídica formal
2. Cite jurisprudência relevante dos tribunais superiores
3. Estruture o documento com todas as partes necessárias
4. Inclua argumentos constitucionais pertinentes
5. Faça referências específicas ao CPP
ESTRUTURA REQUERIDA:
- Cabeçalho completo com qualificação
- Fatos detalhados
- Fundamentos jurídicos
- Jurisprudência aplicável
- Pedidos liminar e final
""",
"denuncia_crime": """
Atue como um advogado criminalista experiente e gere uma denúncia criminal detalhada:
DETALHES DO CASO:
{caso_detalhes}
REQUISITOS:
1. Descreva os fatos com precisão temporal
2. Tipifique corretamente a conduta
3. Indique as circunstâncias do crime
4. Qualifique todos os envolvidos
5. Indique as provas disponíveis
ESTRUTURA:
- Qualificação completa
- Narrativa dos fatos
- Tipificação penal
- Pedidos
- Provas a produzir
""",
"recurso_especial": """
Atue como um advogado criminalista e gere um Recurso Especial Criminal:
CASO E DECISÃO RECORRIDA:
{caso_detalhes}
REQUISITOS:
1. Demonstre o prequestionamento
2. Indique violação à lei federal
3. Cite precedentes do STJ
4. Demonstre divergência jurisprudencial
ESTRUTURA:
- Cabimento e tempestividade
- Prequestionamento
- Mérito recursal
- Pedidos
"""
}
def optimize_prompt(self, doc_type: str, context: Dict[str, str]) -> str:
base_prompt = self.base_prompts.get(doc_type, "")
optimized = base_prompt.format(caso_detalhes=json.dumps(context, indent=2))
return optimized
class LegalDocumentGenerator:
def __init__(self):
self.client = Client("ysharma/Chat_with_Meta_llama3_8b")
self.db = DatabaseManager()
self.prompt_optimizer = PromptOptimizer()
async def generate_document(self, doc_type: str, context: Dict[str, str],
template_id: Optional[int] = None) -> str:
try:
# Otimiza o prompt baseado no tipo de documento
optimized_prompt = self.prompt_optimizer.optimize_prompt(doc_type, context)
# Gera o documento usando a API do Llama
result = await self._generate_with_llama(optimized_prompt)
# Salva o documento gerado
self._save_document(doc_type, result, context)
return result
except Exception as e:
logger.error(f"Erro na geração do documento: {str(e)}")
raise
async def _generate_with_llama(self, prompt: str) -> str:
return self.client.predict(
message=prompt,
request=0.85, # Temperatura reduzida para maior consistência
param_3=3072, # Aumentado para documentos mais longos
api_name="/chat"
)
def _save_document(self, doc_type: str, content: str, context: Dict[str, str]):
with sqlite3.connect(self.db.db_path) as conn:
conn.execute("""
INSERT INTO documents
(title, doc_type, content, created_at, client_name, process_number)
VALUES (?, ?, ?, ?, ?, ?)
""", (
f"{doc_type}_{context.get('client_name')}",
doc_type,
content,
datetime.now(),
context.get('client_name'),
context.get('process_number')
))
class AdvancedLegalInterface:
def __init__(self):
self.generator = LegalDocumentGenerator()
self.create_interface()
def create_interface(self):
with gr.Blocks(theme=gr.themes.Glass()) as self.app:
gr.Markdown("""
# Sistema Avançado de Geração de Peças Criminais
### Powered by LLM Technology
""")
with gr.Tabs():
with gr.Tab("Gerar Documento"):
with gr.Row():
with gr.Column():
doc_type = gr.Dropdown(
choices=[
"Habeas Corpus",
"Denúncia Criminal",
"Recurso Especial",
"Alegações Finais",
"Resposta à Acusação",
"Revisão Criminal",
"Apelação Criminal"
],
label="Tipo de Documento"
)
client_info = gr.Group()
with client_info:
client_name = gr.Textbox(label="Nome do Cliente")
process_number = gr.Textbox(label="Número do Processo")
court = gr.Textbox(label="Tribunal")
jurisdiction = gr.Textbox(label="Comarca")
case_details = gr.Group()
with case_details:
facts = gr.Textbox(
label="Fatos",
lines=5,
placeholder="Descreva os fatos relevantes..."
)
legal_basis = gr.Textbox(
label="Fundamentos Jurídicos",
lines=3,
placeholder="Indique os principais fundamentos legais..."
)
advanced_options = gr.Group()
with advanced_options:
use_template = gr.Checkbox(label="Usar Template Personalizado")
template_select = gr.Dropdown(
choices=self._get_templates(),
label="Template",
visible=False
)
include_jurisprudence = gr.Checkbox(
label="Incluir Jurisprudência Relevante"
)
generate_btn = gr.Button("Gerar Documento", variant="primary")
with gr.Column():
output = gr.Textbox(
label="Documento Gerado",
lines=30,
show_copy_button=True
)
with gr.Row():
save_btn = gr.Button("Salvar Documento")
export_btn = gr.Button("Exportar como PDF")
with gr.Tab("Gerenciar Templates"):
self._create_template_manager()
with gr.Tab("Histórico"):
self._create_history_viewer()
# Eventos
generate_btn.click(
fn=self._generate_document,
inputs=[
doc_type, client_name, process_number, court,
jurisdiction, facts, legal_basis, use_template,
template_select, include_jurisprudence
],
outputs=output
)
use_template.change(
fn=lambda x: gr.update(visible=x),
inputs=[use_template],
outputs=[template_select]
)
def _get_templates(self) -> List[str]:
with sqlite3.connect(self.generator.db.db_path) as conn:
templates = conn.execute("SELECT name FROM templates").fetchall()
return [t[0] for t in templates]
def _create_template_manager(self):
with gr.Group():
gr.Markdown("### Gerenciar Templates")
template_name = gr.Textbox(label="Nome do Template")
template_content = gr.Textbox(label="Conteúdo", lines=10)
save_template_btn = gr.Button("Salvar Template")
def _create_history_viewer(self):
with gr.Group():
gr.Markdown("### Histórico de Documentos")
history_table = gr.Dataframe(
headers=["Data", "Tipo", "Cliente", "Processo"],
row_count=10
)
async def _generate_document(self, *args) -> str:
try:
context = {
"client_name": args[1],
"process_number": args[2],
"court": args[3],
"jurisdiction": args[4],
"facts": args[5],
"legal_basis": args[6],
"use_template": args[7],
"template": args[8] if args[7] else None,
"include_jurisprudence": args[9]
}
result = await self.generator.generate_document(
doc_type=args[0].lower().replace(" ", "_"),
context=context
)
return result
except Exception as e:
logger.error(f"Erro na geração: {str(e)}")
return f"Erro na geração do documento: {str(e)}"
def launch(self):
self.app.launch(share=True)
if __name__ == "__main__":
interface = AdvancedLegalInterface()
interface.launch() |