Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,218 +1,84 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
-
from huggingface_hub import
|
4 |
-
from datetime import datetime
|
5 |
-
import logging
|
6 |
-
from typing import Dict, List
|
7 |
|
8 |
-
#
|
9 |
-
|
10 |
-
|
|
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
def __init__(self):
|
16 |
-
# Usando modelo BERT português
|
17 |
-
self.client = InferenceApi(
|
18 |
-
repo_id="neuralmind/bert-base-portuguese-legal-cased",
|
19 |
-
token=os.environ.get("HF_TOKEN")
|
20 |
-
)
|
21 |
-
|
22 |
-
def generate(self, doc_type: str, context: Dict[str, str]) -> str:
|
23 |
-
"""Gera o documento usando o modelo"""
|
24 |
-
try:
|
25 |
-
prompt = f"""[DOCUMENTO LEGAL]
|
26 |
-
TIPO: {doc_type}
|
27 |
-
|
28 |
-
[QUALIFICAÇÃO]
|
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 |
-
|
38 |
-
|
|
|
|
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
-
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
-
|
50 |
-
response = self.client.text_generation(
|
51 |
-
prompt,
|
52 |
-
max_new_tokens=1024,
|
53 |
-
do_sample=True,
|
54 |
-
temperature=0.2,
|
55 |
-
top_p=0.95,
|
56 |
-
num_return_sequences=1,
|
57 |
-
repetition_penalty=1.2
|
58 |
-
)
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
# Remove o prompt
|
72 |
-
text = text.split("Gere o documento completo em português:")[-1].strip()
|
73 |
-
|
74 |
-
# Ajusta formatação
|
75 |
-
lines = [line.strip() for line in text.split('\n') if line.strip()]
|
76 |
-
formatted_text = '\n\n'.join(lines)
|
77 |
-
|
78 |
-
# Adiciona data
|
79 |
-
current_date = datetime.now().strftime('%d de %B de %Y').replace('May', 'Maio').replace('April', 'Abril')
|
80 |
-
formatted_text = f"{formatted_text}\n\n{context.get('jurisdiction')}, {current_date}"
|
81 |
-
|
82 |
-
return formatted_text.strip()
|
83 |
-
|
84 |
-
class WebInterface:
|
85 |
-
"""Interface Gradio para o gerador de documentos"""
|
86 |
-
|
87 |
-
def __init__(self):
|
88 |
-
self.generator = DocumentGenerator()
|
89 |
-
self.create_interface()
|
90 |
-
|
91 |
-
def create_interface(self):
|
92 |
-
"""Cria a interface web com Gradio"""
|
93 |
|
94 |
-
with gr.
|
95 |
-
gr.
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
with gr.Row():
|
101 |
-
with gr.Column():
|
102 |
-
doc_type = gr.Dropdown(
|
103 |
-
choices=[
|
104 |
-
"Habeas Corpus",
|
105 |
-
"Denúncia Criminal",
|
106 |
-
"Alegações Finais",
|
107 |
-
"Resposta à Acusação",
|
108 |
-
"Recurso em Sentido Estrito",
|
109 |
-
"Apelação Criminal"
|
110 |
-
],
|
111 |
-
label="Tipo de Documento",
|
112 |
-
value="Habeas Corpus"
|
113 |
-
)
|
114 |
-
|
115 |
-
with gr.Group():
|
116 |
-
gr.Markdown("### Informações do Processo")
|
117 |
-
client_name = gr.Textbox(
|
118 |
-
label="Nome do Cliente",
|
119 |
-
placeholder="Nome completo"
|
120 |
-
)
|
121 |
-
process_number = gr.Textbox(
|
122 |
-
label="Número do Processo",
|
123 |
-
placeholder="NNNNNNN-NN.NNNN.N.NN.NNNN"
|
124 |
-
)
|
125 |
-
court = gr.Textbox(
|
126 |
-
label="Tribunal",
|
127 |
-
value="TRIBUNAL DE JUSTIÇA DO ESTADO"
|
128 |
-
)
|
129 |
-
jurisdiction = gr.Textbox(
|
130 |
-
label="Comarca",
|
131 |
-
placeholder="Nome da comarca"
|
132 |
-
)
|
133 |
-
|
134 |
-
with gr.Group():
|
135 |
-
gr.Markdown("### Detalhes do Caso")
|
136 |
-
facts = gr.Textbox(
|
137 |
-
label="Fatos",
|
138 |
-
lines=5,
|
139 |
-
placeholder="Descreva os fatos relevantes..."
|
140 |
-
)
|
141 |
-
legal_basis = gr.Textbox(
|
142 |
-
label="Fundamentos Jurídicos",
|
143 |
-
lines=3,
|
144 |
-
placeholder="Fundamentos legais..."
|
145 |
-
)
|
146 |
-
|
147 |
-
generate_btn = gr.Button("📝 Gerar Documento", variant="primary")
|
148 |
-
|
149 |
-
with gr.Column():
|
150 |
-
output = gr.Textbox(
|
151 |
-
label="Documento Gerado",
|
152 |
-
lines=30,
|
153 |
-
show_copy_button=True
|
154 |
-
)
|
155 |
-
|
156 |
-
# Exemplos
|
157 |
-
gr.Examples(
|
158 |
-
examples=[
|
159 |
-
[
|
160 |
-
"Habeas Corpus",
|
161 |
-
"João da Silva Santos",
|
162 |
-
"0000123-45.2024.8.26.0000",
|
163 |
-
"TRIBUNAL DE JUSTIÇA DO ESTADO DE SÃO PAULO",
|
164 |
-
"São Paulo",
|
165 |
-
"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.",
|
166 |
-
"Art. 5º, LXVIII, CF/88; Art. 647 do CPP; Ausência dos requisitos do Art. 312 do CPP. Súmula 308 STJ."
|
167 |
-
]
|
168 |
-
],
|
169 |
-
inputs=[
|
170 |
-
doc_type, client_name, process_number,
|
171 |
-
court, jurisdiction, facts, legal_basis
|
172 |
-
]
|
173 |
)
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
fn=self._generate_document,
|
178 |
-
inputs=[
|
179 |
-
doc_type, client_name, process_number,
|
180 |
-
court, jurisdiction, facts, legal_basis
|
181 |
-
],
|
182 |
-
outputs=output
|
183 |
)
|
184 |
-
|
185 |
-
def _generate_document(
|
186 |
-
self, doc_type: str, client_name: str,
|
187 |
-
process_number: str, court: str,
|
188 |
-
jurisdiction: str, facts: str,
|
189 |
-
legal_basis: str
|
190 |
-
) -> str:
|
191 |
-
"""Gera o documento com os parâmetros fornecidos"""
|
192 |
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
"jurisdiction": jurisdiction,
|
202 |
-
"facts": facts,
|
203 |
-
"legal_basis": legal_basis
|
204 |
-
}
|
205 |
-
|
206 |
-
return self.generator.generate(doc_type, context)
|
207 |
-
|
208 |
-
except Exception as e:
|
209 |
-
logger.error(f"Erro: {str(e)}")
|
210 |
-
return f"Erro na geração: {str(e)}"
|
211 |
|
212 |
-
|
213 |
-
"""Inicia a interface web"""
|
214 |
-
self.app.launch(share=True)
|
215 |
|
|
|
216 |
if __name__ == "__main__":
|
217 |
-
|
218 |
-
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
+
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
4 |
|
5 |
+
# Obtendo a API Key da variável de ambiente
|
6 |
+
api_key = os.getenv("HF_API_KEY")
|
7 |
+
if not api_key:
|
8 |
+
raise EnvironmentError("A variável de ambiente 'HF_API_KEY' não está configurada.")
|
9 |
|
10 |
+
# Criação do cliente com a API Key
|
11 |
+
client = InferenceClient(api_key=api_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
# Função para gerar a peça jurídica em português
|
14 |
+
def gerar_peca_juridica_criminal(informacoes_caso, tipo_peca):
|
15 |
+
"""
|
16 |
+
Gera uma peça jurídica criminal em português com base no tipo e nas informações fornecidas.
|
17 |
|
18 |
+
Parâmetros:
|
19 |
+
informacoes_caso (str): Descrição detalhada do caso.
|
20 |
+
tipo_peca (str): Tipo de peça jurídica a ser gerada (ex: habeas corpus, petição inicial).
|
21 |
+
|
22 |
+
Retorna:
|
23 |
+
str: Peça jurídica gerada.
|
24 |
+
"""
|
25 |
+
mensagens = [
|
26 |
+
{
|
27 |
+
"role": "system",
|
28 |
+
"content": (
|
29 |
+
"Você é um especialista em direito criminal no Brasil e deve gerar peças jurídicas detalhadas. "
|
30 |
+
"Todas as respostas devem estar em português, considerando o ordenamento jurídico brasileiro."
|
31 |
+
)
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"role": "user",
|
35 |
+
"content": f"Quero que você elabore um(a) {tipo_peca} com base nas seguintes informações do caso: {informacoes_caso}"
|
36 |
+
}
|
37 |
+
]
|
38 |
|
39 |
+
# Chamada ao modelo para gerar a resposta
|
40 |
+
resposta = client.chat.completions.create(
|
41 |
+
model="mistralai/Mistral-7B-Instruct-v0.3",
|
42 |
+
messages=mensagens,
|
43 |
+
max_tokens=1000
|
44 |
+
)
|
45 |
|
46 |
+
return resposta.choices[0].message["content"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
+
# Configuração do app Gradio
|
49 |
+
def gerar_interface_gradio():
|
50 |
+
"""
|
51 |
+
Configura a interface do Gradio para gerar peças jurídicas.
|
52 |
+
"""
|
53 |
+
with gr.Blocks() as interface:
|
54 |
+
gr.Markdown("## Gerador de Peças Jurídicas Criminais")
|
55 |
+
gr.Markdown(
|
56 |
+
"Insira as informações detalhadas do caso e escolha o tipo de peça jurídica que deseja gerar."
|
57 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
+
with gr.Row():
|
60 |
+
entrada_caso = gr.Textbox(
|
61 |
+
label="Informações do Caso",
|
62 |
+
placeholder="Descreva o caso detalhadamente aqui...",
|
63 |
+
lines=5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
)
|
65 |
+
entrada_tipo = gr.Textbox(
|
66 |
+
label="Tipo de Peça Jurídica",
|
67 |
+
placeholder="Exemplo: habeas corpus, petição inicial..."
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
+
botao_gerar = gr.Button("Gerar Peça Jurídica")
|
71 |
+
saida_texto = gr.Textbox(label="Peça Jurídica Gerada", lines=15)
|
72 |
+
|
73 |
+
botao_gerar.click(
|
74 |
+
gerar_peca_juridica_criminal,
|
75 |
+
inputs=[entrada_caso, entrada_tipo],
|
76 |
+
outputs=saida_texto
|
77 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
+
return interface
|
|
|
|
|
80 |
|
81 |
+
# Executa o app
|
82 |
if __name__ == "__main__":
|
83 |
+
app = gerar_interface_gradio()
|
84 |
+
app.launch()
|