Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
from datetime import datetime
|
@@ -8,51 +9,72 @@ from typing import Dict, List, Optional
|
|
8 |
logging.basicConfig(level=logging.INFO)
|
9 |
logger = logging.getLogger(__name__)
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
class DocumentGenerator:
|
12 |
-
"""Gerencia a geração de documentos usando
|
13 |
|
14 |
-
def __init__(self):
|
15 |
-
|
16 |
-
self.client = InferenceClient()
|
17 |
self.model = "mistralai/Mistral-7B-Instruct-v0.2"
|
|
|
18 |
|
19 |
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
|
20 |
-
"""Gera o documento
|
21 |
try:
|
22 |
-
# Prepara
|
23 |
-
|
24 |
-
Gere o documento solicitado usando linguagem formal, técnica e no formato jurídico correto."""
|
25 |
-
|
26 |
-
user_content = f"""Gere um {doc_type} com os seguintes dados:
|
27 |
-
|
28 |
-
DADOS DO CASO:
|
29 |
-
Cliente: {context.get('client_name')}
|
30 |
-
Processo: {context.get('process_number')}
|
31 |
-
Tribunal: {context.get('court')}
|
32 |
-
Comarca: {context.get('jurisdiction')}
|
33 |
-
|
34 |
-
FATOS:
|
35 |
-
{context.get('facts')}
|
36 |
-
|
37 |
-
FUNDAMENTOS JURÍDICOS:
|
38 |
-
{context.get('legal_basis')}
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
messages = [
|
43 |
-
{"role": "system", "content": system_prompt},
|
44 |
-
{"role": "user", "content": user_content}
|
45 |
-
]
|
46 |
-
|
47 |
-
# Faz a chamada ao modelo
|
48 |
completion = self.client.chat.completions.create(
|
49 |
model=self.model,
|
50 |
messages=messages,
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
)
|
55 |
-
|
56 |
return self._format_output(completion.choices[0].message.content)
|
57 |
|
58 |
except Exception as e:
|
@@ -63,13 +85,18 @@ class DocumentGenerator:
|
|
63 |
"""Formata o texto gerado"""
|
64 |
if not text:
|
65 |
return "Erro: Nenhum texto gerado"
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
class WebInterface:
|
69 |
"""Interface Gradio para o gerador de documentos"""
|
70 |
|
71 |
def __init__(self):
|
72 |
-
self.generator = DocumentGenerator()
|
73 |
self.create_interface()
|
74 |
|
75 |
def create_interface(self):
|
@@ -77,88 +104,118 @@ class WebInterface:
|
|
77 |
|
78 |
with gr.Blocks(theme=gr.themes.Soft()) as self.app:
|
79 |
gr.Markdown("""
|
80 |
-
# Gerador de
|
81 |
-
###
|
82 |
""")
|
83 |
|
84 |
with gr.Row():
|
85 |
with gr.Column():
|
86 |
-
#
|
87 |
doc_type = gr.Dropdown(
|
88 |
choices=[
|
89 |
"Habeas Corpus",
|
90 |
-
"Denúncia",
|
91 |
"Alegações Finais",
|
92 |
"Resposta à Acusação",
|
93 |
"Recurso em Sentido Estrito",
|
94 |
"Apelação Criminal"
|
95 |
],
|
96 |
label="Tipo de Documento",
|
97 |
-
value="Habeas Corpus"
|
|
|
98 |
)
|
99 |
|
100 |
# Informações do processo
|
101 |
with gr.Group():
|
102 |
gr.Markdown("### Informações do Processo")
|
|
|
103 |
client_name = gr.Textbox(
|
104 |
label="Nome do Cliente",
|
105 |
-
placeholder="Nome completo do cliente"
|
|
|
106 |
)
|
|
|
107 |
process_number = gr.Textbox(
|
108 |
label="Número do Processo",
|
109 |
-
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN"
|
|
|
110 |
)
|
|
|
111 |
court = gr.Textbox(
|
112 |
label="Tribunal",
|
113 |
-
value="TRIBUNAL DE JUSTIÇA DO ESTADO"
|
|
|
114 |
)
|
|
|
115 |
jurisdiction = gr.Textbox(
|
116 |
label="Comarca",
|
117 |
-
placeholder="
|
|
|
118 |
)
|
119 |
|
120 |
# Detalhes do caso
|
121 |
with gr.Group():
|
122 |
gr.Markdown("### Detalhes do Caso")
|
|
|
123 |
facts = gr.Textbox(
|
124 |
label="Fatos",
|
125 |
lines=5,
|
126 |
-
placeholder="Descreva os fatos relevantes do caso..."
|
|
|
127 |
)
|
|
|
128 |
legal_basis = gr.Textbox(
|
129 |
label="Fundamentos Jurídicos",
|
130 |
lines=3,
|
131 |
-
placeholder="Indique os fundamentos legais
|
|
|
132 |
)
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
)
|
138 |
|
|
|
139 |
with gr.Column():
|
140 |
output = gr.Textbox(
|
141 |
label="Documento Gerado",
|
142 |
lines=30,
|
143 |
-
show_copy_button=True
|
|
|
|
|
144 |
)
|
145 |
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
)
|
150 |
|
151 |
-
#
|
152 |
gr.Examples(
|
153 |
examples=[
|
154 |
[
|
155 |
"Habeas Corpus",
|
156 |
-
"João da Silva",
|
157 |
"0000123-45.2024.8.26.0000",
|
158 |
"TRIBUNAL DE JUSTIÇA DO ESTADO DE SÃO PAULO",
|
159 |
"São Paulo",
|
160 |
-
"Paciente preso em flagrante no dia 25/12/2024 por suposto furto
|
161 |
-
"Art. 5º, LXVIII da CF/88; Art. 647 do CPP;
|
162 |
]
|
163 |
],
|
164 |
inputs=[
|
@@ -176,6 +233,42 @@ class WebInterface:
|
|
176 |
],
|
177 |
outputs=[output, status]
|
178 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
|
180 |
def _generate_document(
|
181 |
self, doc_type: str, client_name: str,
|
@@ -188,7 +281,7 @@ class WebInterface:
|
|
188 |
try:
|
189 |
# Validação básica
|
190 |
if not all([client_name, process_number, facts, legal_basis]):
|
191 |
-
return "Erro: Todos os campos obrigatórios devem ser preenchidos", "⚠️ Preencha todos os campos obrigatórios"
|
192 |
|
193 |
context = {
|
194 |
"client_name": client_name,
|
@@ -203,10 +296,7 @@ class WebInterface:
|
|
203 |
yield "", "⏳ Gerando documento..."
|
204 |
|
205 |
# Gera documento
|
206 |
-
result = self.generator.generate(
|
207 |
-
doc_type,
|
208 |
-
context
|
209 |
-
)
|
210 |
|
211 |
return result, "✅ Documento gerado com sucesso!"
|
212 |
|
@@ -216,8 +306,13 @@ class WebInterface:
|
|
216 |
|
217 |
def launch(self):
|
218 |
"""Inicia a interface web"""
|
219 |
-
self.app.launch()
|
220 |
|
221 |
if __name__ == "__main__":
|
222 |
-
|
223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
from huggingface_hub import InferenceClient
|
4 |
from datetime import datetime
|
|
|
9 |
logging.basicConfig(level=logging.INFO)
|
10 |
logger = logging.getLogger(__name__)
|
11 |
|
12 |
+
# Substitua com sua chave de API
|
13 |
+
HF_API_KEY = "hf_seu_token_aqui"
|
14 |
+
|
15 |
+
class DocumentManager:
|
16 |
+
"""Gerencia templates e contextos dos documentos"""
|
17 |
+
|
18 |
+
@staticmethod
|
19 |
+
def create_prompt_messages(doc_type: str, context: Dict[str, str]) -> List[Dict[str, str]]:
|
20 |
+
"""Cria a sequência de mensagens para o modelo"""
|
21 |
+
|
22 |
+
system_message = {
|
23 |
+
"role": "system",
|
24 |
+
"content": """Você é um advogado criminalista brasileiro altamente experiente, especializado em redigir peças processuais.
|
25 |
+
Gere documentos jurídicos formais, tecnicamente precisos e no formato do direito brasileiro."""
|
26 |
+
}
|
27 |
+
|
28 |
+
user_message = {
|
29 |
+
"role": "user",
|
30 |
+
"content": f"""Por favor, gere um {doc_type} completo e tecnicamente preciso com os seguintes dados:
|
31 |
+
|
32 |
+
QUALIFICAÇÃO:
|
33 |
+
Cliente: {context.get('client_name')}
|
34 |
+
Processo: {context.get('process_number')}
|
35 |
+
Tribunal: {context.get('court')}
|
36 |
+
Comarca: {context.get('jurisdiction')}
|
37 |
+
|
38 |
+
FATOS:
|
39 |
+
{context.get('facts')}
|
40 |
+
|
41 |
+
FUNDAMENTOS JURÍDICOS:
|
42 |
+
{context.get('legal_basis')}
|
43 |
+
|
44 |
+
O documento deve seguir a formatação jurídica padrão, incluindo:
|
45 |
+
1. Cabeçalho com endereçamento correto
|
46 |
+
2. Qualificação completa das partes
|
47 |
+
3. Exposição clara dos fatos
|
48 |
+
4. Fundamentação jurídica sólida
|
49 |
+
5. Pedidos específicos
|
50 |
+
6. Fechamento formal com local, data e espaço para assinatura"""
|
51 |
+
}
|
52 |
+
|
53 |
+
return [system_message, user_message]
|
54 |
+
|
55 |
class DocumentGenerator:
|
56 |
+
"""Gerencia a geração de documentos usando HuggingFace Inference API"""
|
57 |
|
58 |
+
def __init__(self, api_key: str):
|
59 |
+
self.client = InferenceClient(api_key=api_key)
|
|
|
60 |
self.model = "mistralai/Mistral-7B-Instruct-v0.2"
|
61 |
+
self.doc_manager = DocumentManager()
|
62 |
|
63 |
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
|
64 |
+
"""Gera o documento usando o modelo"""
|
65 |
try:
|
66 |
+
# Prepara as mensagens
|
67 |
+
messages = self.doc_manager.create_prompt_messages(doc_type, context)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
+
# Faz a chamada à API
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
completion = self.client.chat.completions.create(
|
71 |
model=self.model,
|
72 |
messages=messages,
|
73 |
+
temperature=0.3, # Mais conservador para documentos formais
|
74 |
+
top_p=0.85, # Mantém coerência
|
75 |
+
max_tokens=2048, # Documento completo
|
76 |
)
|
77 |
+
|
78 |
return self._format_output(completion.choices[0].message.content)
|
79 |
|
80 |
except Exception as e:
|
|
|
85 |
"""Formata o texto gerado"""
|
86 |
if not text:
|
87 |
return "Erro: Nenhum texto gerado"
|
88 |
+
|
89 |
+
# Remove espaços extras e formata parágrafos
|
90 |
+
lines = [line.strip() for line in text.split('\n') if line.strip()]
|
91 |
+
formatted_text = '\n\n'.join(lines)
|
92 |
+
|
93 |
+
return formatted_text.strip()
|
94 |
|
95 |
class WebInterface:
|
96 |
"""Interface Gradio para o gerador de documentos"""
|
97 |
|
98 |
def __init__(self):
|
99 |
+
self.generator = DocumentGenerator(api_key=HF_API_KEY)
|
100 |
self.create_interface()
|
101 |
|
102 |
def create_interface(self):
|
|
|
104 |
|
105 |
with gr.Blocks(theme=gr.themes.Soft()) as self.app:
|
106 |
gr.Markdown("""
|
107 |
+
# Criminal.ai - Gerador de Peças Processuais
|
108 |
+
### Sistema Inteligente de Geração de Documentos Jurídicos
|
109 |
""")
|
110 |
|
111 |
with gr.Row():
|
112 |
with gr.Column():
|
113 |
+
# Tipo de documento
|
114 |
doc_type = gr.Dropdown(
|
115 |
choices=[
|
116 |
"Habeas Corpus",
|
117 |
+
"Denúncia Criminal",
|
118 |
"Alegações Finais",
|
119 |
"Resposta à Acusação",
|
120 |
"Recurso em Sentido Estrito",
|
121 |
"Apelação Criminal"
|
122 |
],
|
123 |
label="Tipo de Documento",
|
124 |
+
value="Habeas Corpus",
|
125 |
+
info="Selecione o tipo de peça processual"
|
126 |
)
|
127 |
|
128 |
# Informações do processo
|
129 |
with gr.Group():
|
130 |
gr.Markdown("### Informações do Processo")
|
131 |
+
|
132 |
client_name = gr.Textbox(
|
133 |
label="Nome do Cliente",
|
134 |
+
placeholder="Nome completo do cliente/paciente",
|
135 |
+
info="Digite o nome completo"
|
136 |
)
|
137 |
+
|
138 |
process_number = gr.Textbox(
|
139 |
label="Número do Processo",
|
140 |
+
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN",
|
141 |
+
info="Número CNJ do processo"
|
142 |
)
|
143 |
+
|
144 |
court = gr.Textbox(
|
145 |
label="Tribunal",
|
146 |
+
value="TRIBUNAL DE JUSTIÇA DO ESTADO",
|
147 |
+
info="Nome completo do tribunal"
|
148 |
)
|
149 |
+
|
150 |
jurisdiction = gr.Textbox(
|
151 |
label="Comarca",
|
152 |
+
placeholder="Nome da comarca",
|
153 |
+
info="Comarca onde tramita o processo"
|
154 |
)
|
155 |
|
156 |
# Detalhes do caso
|
157 |
with gr.Group():
|
158 |
gr.Markdown("### Detalhes do Caso")
|
159 |
+
|
160 |
facts = gr.Textbox(
|
161 |
label="Fatos",
|
162 |
lines=5,
|
163 |
+
placeholder="Descreva os fatos relevantes do caso...",
|
164 |
+
info="Descreva os fatos de forma clara e objetiva"
|
165 |
)
|
166 |
+
|
167 |
legal_basis = gr.Textbox(
|
168 |
label="Fundamentos Jurídicos",
|
169 |
lines=3,
|
170 |
+
placeholder="Indique os fundamentos legais...",
|
171 |
+
info="Artigos, jurisprudência e doutrina aplicáveis"
|
172 |
)
|
173 |
|
174 |
+
# Status e botões
|
175 |
+
with gr.Row():
|
176 |
+
generate_btn = gr.Button(
|
177 |
+
"📝 Gerar Documento",
|
178 |
+
variant="primary",
|
179 |
+
scale=2
|
180 |
+
)
|
181 |
+
|
182 |
+
clear_btn = gr.Button(
|
183 |
+
"🗑️ Limpar",
|
184 |
+
variant="secondary",
|
185 |
+
scale=1
|
186 |
+
)
|
187 |
+
|
188 |
+
status = gr.Textbox(
|
189 |
+
label="Status",
|
190 |
+
interactive=False,
|
191 |
+
show_label=False
|
192 |
)
|
193 |
|
194 |
+
# Coluna de saída
|
195 |
with gr.Column():
|
196 |
output = gr.Textbox(
|
197 |
label="Documento Gerado",
|
198 |
lines=30,
|
199 |
+
show_copy_button=True,
|
200 |
+
show_label=True,
|
201 |
+
container=True
|
202 |
)
|
203 |
|
204 |
+
with gr.Row():
|
205 |
+
copy_btn = gr.Button("📋 Copiar")
|
206 |
+
download_btn = gr.Button("💾 Salvar como .txt")
|
|
|
207 |
|
208 |
+
# Exemplos
|
209 |
gr.Examples(
|
210 |
examples=[
|
211 |
[
|
212 |
"Habeas Corpus",
|
213 |
+
"João da Silva Santos",
|
214 |
"0000123-45.2024.8.26.0000",
|
215 |
"TRIBUNAL DE JUSTIÇA DO ESTADO DE SÃO PAULO",
|
216 |
"São Paulo",
|
217 |
+
"Paciente preso em flagrante no dia 25/12/2024 por suposto furto simples (art. 155, caput, do CP). Não estão presentes os requisitos da prisão preventiva, sendo o paciente primário, com residência fixa e trabalho lícito.",
|
218 |
+
"Art. 5º, LXVIII da CF/88; Art. 647 do CPP; Art. 312 do CPP; Súmula 308 do STJ."
|
219 |
]
|
220 |
],
|
221 |
inputs=[
|
|
|
233 |
],
|
234 |
outputs=[output, status]
|
235 |
)
|
236 |
+
|
237 |
+
def clear_inputs():
|
238 |
+
return [
|
239 |
+
gr.update(value="") for _ in range(6)
|
240 |
+
] + [gr.update(value="Campos limpos")]
|
241 |
+
|
242 |
+
clear_btn.click(
|
243 |
+
fn=clear_inputs,
|
244 |
+
inputs=[],
|
245 |
+
outputs=[
|
246 |
+
client_name, process_number, court,
|
247 |
+
jurisdiction, facts, legal_basis,
|
248 |
+
status
|
249 |
+
]
|
250 |
+
)
|
251 |
+
|
252 |
+
copy_btn.click(
|
253 |
+
fn=lambda x: gr.update(value=x),
|
254 |
+
inputs=[output],
|
255 |
+
outputs=[output]
|
256 |
+
)
|
257 |
+
|
258 |
+
def save_document(text):
|
259 |
+
if not text:
|
260 |
+
return "Nenhum documento para salvar"
|
261 |
+
|
262 |
+
filename = f"documento_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
263 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
264 |
+
f.write(text)
|
265 |
+
return f"Documento salvo como {filename}"
|
266 |
+
|
267 |
+
download_btn.click(
|
268 |
+
fn=save_document,
|
269 |
+
inputs=[output],
|
270 |
+
outputs=[status]
|
271 |
+
)
|
272 |
|
273 |
def _generate_document(
|
274 |
self, doc_type: str, client_name: str,
|
|
|
281 |
try:
|
282 |
# Validação básica
|
283 |
if not all([client_name, process_number, facts, legal_basis]):
|
284 |
+
return "⚠️ Erro: Todos os campos obrigatórios devem ser preenchidos", "⚠️ Preencha todos os campos obrigatórios"
|
285 |
|
286 |
context = {
|
287 |
"client_name": client_name,
|
|
|
296 |
yield "", "⏳ Gerando documento..."
|
297 |
|
298 |
# Gera documento
|
299 |
+
result = self.generator.generate(doc_type, context)
|
|
|
|
|
|
|
300 |
|
301 |
return result, "✅ Documento gerado com sucesso!"
|
302 |
|
|
|
306 |
|
307 |
def launch(self):
|
308 |
"""Inicia a interface web"""
|
309 |
+
self.app.launch(share=True)
|
310 |
|
311 |
if __name__ == "__main__":
|
312 |
+
# Verificar token
|
313 |
+
if HF_API_KEY == "hf_seu_token_aqui":
|
314 |
+
print("⚠️ Atenção: Configure sua API key do Hugging Face antes de executar!")
|
315 |
+
print("Substitua 'hf_seu_token_aqui' pela sua chave real.")
|
316 |
+
else:
|
317 |
+
interface = WebInterface()
|
318 |
+
interface.launch()
|