Spaces:
Sleeping
Sleeping
File size: 8,422 Bytes
82a745d 716ba45 97f6f5e 716ba45 e411978 322c937 716ba45 2552fb1 322c937 716ba45 322c937 82a745d 322c937 82a745d 322c937 82a745d 97f6f5e 322c937 716ba45 82a745d 322c937 82a745d 97f6f5e 82a745d 97f6f5e 322c937 716ba45 82a745d 97f6f5e 322c937 97f6f5e 82a745d 97f6f5e e411978 97f6f5e 716ba45 2552fb1 97f6f5e 322c937 716ba45 2552fb1 716ba45 322c937 716ba45 2552fb1 716ba45 322c937 716ba45 2552fb1 82a745d 97f6f5e 2552fb1 322c937 2552fb1 322c937 2552fb1 322c937 2552fb1 322c937 2552fb1 322c937 2552fb1 322c937 2552fb1 322c937 82a745d 322c937 716ba45 2552fb1 322c937 2552fb1 322c937 716ba45 2552fb1 716ba45 6891179 716ba45 2552fb1 6891179 2552fb1 6891179 322c937 6891179 82a745d 322c937 6891179 716ba45 2552fb1 82a745d 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
import os
import gradio as gr
from huggingface_hub import InferenceClient
from datetime import datetime
import logging
from typing import Dict, List, Optional
from pathlib import Path
import json
import dotenv
# Carrega variáveis de ambiente do arquivo .env se existir
dotenv.load_dotenv()
# Configuração do logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def load_token() -> str:
"""Carrega o token HF de várias fontes possíveis"""
# Prioridade: 1. Variável de ambiente, 2. Arquivo .env, 3. arquivo config.json
# Verifica variável de ambiente
token = os.getenv('HF_TOKEN')
if token:
return token
# Verifica arquivo config.json
config_file = Path('config.json')
if config_file.exists():
try:
with open(config_file, 'r') as f:
config = json.load(f)
return config.get('hf_token', '')
except Exception as e:
logger.error(f"Erro ao ler config.json: {e}")
return ''
# Carrega o token
HF_API_TOKEN = load_token()
class DocumentGenerator:
"""Gerencia a geração de documentos usando HF Inference API"""
def __init__(self, api_key: str):
if not api_key:
raise ValueError("API Key não encontrada. Configure HF_TOKEN nas variáveis de ambiente ou no arquivo config.json")
self.client = InferenceClient(api_key=api_key)
self.model = "mistralai/Mistral-7B-Instruct-v0.2"
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
"""Gera o documento usando o modelo"""
try:
# Prepara as mensagens para o chat
messages = [
{
"role": "system",
"content": """Você é um advogado criminalista brasileiro experiente.
Gere documentos jurídicos formais no formato do direito brasileiro."""
},
{
"role": "user",
"content": f"""Gere um {doc_type} completo com os seguintes dados:
QUALIFICAÇÃO:
Cliente: {context.get('client_name')}
Processo: {context.get('process_number')}
Tribunal: {context.get('court')}
Comarca: {context.get('jurisdiction')}
FATOS:
{context.get('facts')}
FUNDAMENTOS JURÍDICOS:
{context.get('legal_basis')}
Use formato jurídico adequado, com todas as partes necessárias."""
}
]
# Faz a chamada à API
completion = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.3,
top_p=0.85,
max_tokens=2048,
)
return self._format_output(completion.choices[0].message.content)
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"
return text.strip()
class WebInterface:
"""Interface Gradio para o gerador de documentos"""
def __init__(self):
self.generator = DocumentGenerator(api_key=HF_API_TOKEN)
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 Documentos Jurídicos
Sistema de geração de peças processuais criminais
""")
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"
)
with gr.Group():
gr.Markdown("### Detalhes do Caso")
facts = gr.Textbox(
label="Fatos",
lines=5,
placeholder="Descreva os fatos..."
)
legal_basis = gr.Textbox(
label="Fundamentos Jurídicos",
lines=3
)
generate_btn = gr.Button("Gerar Documento", variant="primary")
with gr.Column():
output = gr.Textbox(
label="Documento Gerado",
lines=30,
show_copy_button=True
)
status = gr.Textbox(label="Status")
# Eventos
generate_btn.click(
fn=self._generate_document,
inputs=[
doc_type, client_name, process_number,
court, jurisdiction, facts, legal_basis
],
outputs=[output, status]
)
def _generate_document(
self, doc_type: str, client_name: str,
process_number: str, court: str,
jurisdiction: str, facts: str,
legal_basis: str
) -> tuple:
"""Gera o documento com os parâmetros fornecidos"""
try:
if not all([client_name, process_number, facts, legal_basis]):
return "Erro: Preencha todos os campos obrigatórios", "⚠️ Campos incompletos"
context = {
"client_name": client_name,
"process_number": process_number,
"court": court,
"jurisdiction": jurisdiction,
"facts": facts,
"legal_basis": legal_basis
}
result = self.generator.generate(doc_type, context)
return result, "✅ Documento gerado com sucesso"
except Exception as e:
logger.error(f"Erro: {str(e)}")
return "", f"❌ Erro: {str(e)}"
def launch(self):
"""Inicia a interface web"""
self.app.launch(share=True)
if __name__ == "__main__":
# Verifica se o token está configurado
if not HF_API_TOKEN:
print("\n⚠️ Token HF não encontrado!")
print("\nPara configurar o token:")
print("1. Crie um arquivo .env com:")
print(" HF_TOKEN=seu_token_aqui")
print("\nOu")
print("2. Crie um arquivo config.json com:")
print(' {"hf_token": "seu_token_aqui"}')
print("\nOu")
print("3. Configure a variável de ambiente HF_TOKEN")
exit(1)
interface = WebInterface()
interface.launch() |