Spaces:
Running
Running
File size: 7,916 Bytes
82a745d 716ba45 428cd1d 716ba45 428cd1d 716ba45 2552fb1 942d705 716ba45 97f6f5e 99c1a44 716ba45 942d705 99c1a44 d5649b7 97f6f5e 99c1a44 97f6f5e 99c1a44 d5649b7 99c1a44 97f6f5e d5649b7 99c1a44 82a745d e411978 97f6f5e 716ba45 2552fb1 97f6f5e 99c1a44 428cd1d 99c1a44 d5649b7 428cd1d d5649b7 99c1a44 428cd1d 716ba45 2552fb1 716ba45 942d705 716ba45 2552fb1 716ba45 bd07d48 716ba45 2552fb1 82a745d 97f6f5e 2552fb1 942d705 2552fb1 428cd1d 2552fb1 942d705 2552fb1 942d705 2552fb1 bd07d48 942d705 2552fb1 942d705 2552fb1 bd07d48 428cd1d 82a745d 428cd1d 716ba45 2552fb1 322c937 2552fb1 bd07d48 428cd1d bd07d48 716ba45 2552fb1 716ba45 428cd1d bd07d48 716ba45 2552fb1 428cd1d 2552fb1 428cd1d 6891179 428cd1d 6891179 428cd1d 6891179 428cd1d 716ba45 2552fb1 428cd1d 716ba45 322c937 |
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 |
import os
import gradio as gr
from huggingface_hub import HfApi, InferenceApi
from datetime import datetime
import logging
from typing import Dict, List
# Configuração do logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DocumentGenerator:
"""Gerencia a geração de documentos usando modelo público"""
def __init__(self):
# Usando um Space público que está efetivamente disponível
self.client = InferenceApi(
repo_id="OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5",
token=os.environ.get("HF_TOKEN")
)
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
"""Gera o documento usando o modelo"""
try:
prompt = f"""You are a Brazilian criminal lawyer. Create a {doc_type} in Portuguese following Brazilian legal standards.
Information:
Client: {context.get('client_name')}
Process: {context.get('process_number')}
Court: {context.get('court')}
Jurisdiction: {context.get('jurisdiction')}
Facts:
{context.get('facts')}
Legal Basis:
{context.get('legal_basis')}
Instructions:
1. Use formal legal Portuguese
2. Follow Brazilian legal document format
3. Include all required sections
4. Be precise and clear
5. Keep proper legal formatting"""
response = self.client(
inputs=prompt,
parameters={
"max_new_tokens": 2048,
"temperature": 0.3,
"top_p": 0.95,
"repetition_penalty": 1.15,
"do_sample": True
}
)
return self._format_output(response[0]["generated_text"])
except Exception as e:
logger.error(f"Erro na geração: {str(e)}")
return f"Erro na geração do documento: {str(e)}"
def _format_output(self, text: str) -> str:
"""Formata o texto gerado"""
if not text:
return "Erro: Nenhum texto gerado"
# Remove o prompt da resposta
text = text.split("Instructions:")[-1].strip()
# Ajusta formatação
lines = [line.strip() for line in text.split('\n') if line.strip()]
formatted_text = '\n\n'.join(lines)
# Adiciona data atual
current_date = datetime.now().strftime('%d de %B de %Y')
formatted_text = f"{formatted_text}\n\n{context.get('jurisdiction')}, {current_date}"
return formatted_text
class WebInterface:
"""Interface Gradio para o gerador de documentos"""
def __init__(self):
self.generator = DocumentGenerator()
self.create_interface()
def create_interface(self):
"""Cria a interface web com Gradio"""
with gr.Blocks(theme=gr.themes.Soft()) as self.app:
gr.Markdown("""
# Criminal.ai - Gerador de Peças Processuais
### Sistema Inteligente para Geração de Documentos Jurídicos
""")
with gr.Row():
with gr.Column():
doc_type = gr.Dropdown(
choices=[
"Habeas Corpus",
"Denúncia Criminal",
"Alegações Finais",
"Resposta à Acusação",
"Recurso em Sentido Estrito",
"Apelação Criminal"
],
label="Tipo de Documento",
value="Habeas Corpus"
)
with gr.Group():
gr.Markdown("### Informações do Processo")
client_name = gr.Textbox(
label="Nome do Cliente",
placeholder="Nome completo"
)
process_number = gr.Textbox(
label="Número do Processo",
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN"
)
court = gr.Textbox(
label="Tribunal",
value="TRIBUNAL DE JUSTIÇA DO ESTADO"
)
jurisdiction = gr.Textbox(
label="Comarca",
placeholder="Nome da comarca"
)
with gr.Group():
gr.Markdown("### Detalhes do Caso")
facts = gr.Textbox(
label="Fatos",
lines=5,
placeholder="Descreva os fatos relevantes..."
)
legal_basis = gr.Textbox(
label="Fundamentos Jurídicos",
lines=3,
placeholder="Fundamentos legais..."
)
generate_btn = gr.Button("📝 Gerar Documento", variant="primary")
with gr.Column():
output = gr.Textbox(
label="Documento Gerado",
lines=30,
show_copy_button=True
)
# Exemplos
gr.Examples(
examples=[
[
"Habeas Corpus",
"João da Silva Santos",
"0000123-45.2024.8.26.0000",
"TRIBUNAL DE JUSTIÇA DO ESTADO DE SÃO PAULO",
"São Paulo",
"Paciente preso em flagrante no dia 25/12/2024 por suposto furto simples (art. 155, caput, CP). O paciente é primário, possui residência fixa no distrito da culpa e ocupação lícita comprovada. Não estão presentes os requisitos autorizadores da prisão preventiva.",
"Art. 5º, LXVIII, CF/88; Art. 647 do CPP; Ausência dos requisitos do Art. 312 do CPP. Súmula 308 STJ."
]
],
inputs=[
doc_type, client_name, process_number,
court, jurisdiction, facts, legal_basis
]
)
# Eventos
generate_btn.click(
fn=self._generate_document,
inputs=[
doc_type, client_name, process_number,
court, jurisdiction, facts, legal_basis
],
outputs=output
)
def _generate_document(
self, doc_type: str, client_name: str,
process_number: str, court: str,
jurisdiction: str, facts: str,
legal_basis: str
) -> str:
"""Gera o documento com os parâmetros fornecidos"""
try:
if not all([client_name, process_number, facts, legal_basis]):
return "Erro: Todos os campos obrigatórios devem ser preenchidos"
context = {
"client_name": client_name,
"process_number": process_number,
"court": court,
"jurisdiction": jurisdiction,
"facts": facts,
"legal_basis": legal_basis
}
return self.generator.generate(doc_type, context)
except Exception as e:
logger.error(f"Erro: {str(e)}")
return f"Erro na geração: {str(e)}"
def launch(self):
"""Inicia a interface web"""
self.app.launch(share=True)
if __name__ == "__main__":
interface = WebInterface()
interface.launch() |