DHEIVER commited on
Commit
e411978
·
verified ·
1 Parent(s): 0a73c27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -112
app.py CHANGED
@@ -1,10 +1,9 @@
1
  import gradio as gr
2
- from gradio_client import Client
3
  import json
4
  from datetime import datetime
5
- import os
6
- from typing import Dict, List, Optional
7
  import logging
 
8
 
9
  # Configuração do logging
10
  logging.basicConfig(
@@ -88,122 +87,41 @@ class PromptManager:
88
  3. Mérito
89
  4. Análise das provas
90
  5. Pedidos
91
- """,
92
-
93
- "resposta_acusacao": f"""
94
- Atue como um advogado criminalista e gere uma resposta à acusação:
95
-
96
- DADOS DO PROCESSO:
97
- Cliente: {context.get('client_name')}
98
- Processo: {context.get('process_number')}
99
- Tribunal: {context.get('court')}
100
-
101
- FATOS:
102
- {context.get('facts')}
103
-
104
- TESE DEFENSIVA:
105
- {context.get('legal_basis')}
106
-
107
- Elabore uma resposta à acusação completa, incluindo:
108
- 1. Preliminares
109
- 2. Mérito
110
- 3. Requerimentos probatórios
111
- 4. Teses defensivas
112
- 5. Pedidos
113
- """,
114
-
115
- "recurso_sentido_estrito": f"""
116
- Atue como um advogado criminalista e gere um recurso em sentido estrito:
117
-
118
- DADOS DO PROCESSO:
119
- Cliente: {context.get('client_name')}
120
- Processo: {context.get('process_number')}
121
- Tribunal: {context.get('court')}
122
-
123
- FATOS:
124
- {context.get('facts')}
125
-
126
- FUNDAMENTOS RECURSAIS:
127
- {context.get('legal_basis')}
128
-
129
- Elabore um recurso em sentido estrito completo, incluindo:
130
- 1. Tempestividade
131
- 2. Cabimento
132
- 3. Fundamentação
133
- 4. Pedidos
134
- """,
135
-
136
- "apelacao_criminal": f"""
137
- Atue como um advogado criminalista e gere uma apelação criminal:
138
-
139
- DADOS DO PROCESSO:
140
- Cliente: {context.get('client_name')}
141
- Processo: {context.get('process_number')}
142
- Tribunal: {context.get('court')}
143
-
144
- FATOS E SENTENÇA:
145
- {context.get('facts')}
146
-
147
- RAZÕES RECURSAIS:
148
- {context.get('legal_basis')}
149
-
150
- Elabore uma apelação criminal completa, incluindo:
151
- 1. Tempestividade
152
- 2. Preliminares
153
- 3. Mérito recursal
154
- 4. Pedidos
155
  """
156
  }
157
 
158
  return prompts.get(doc_type, "Tipo de documento não suportado")
159
 
160
  class DocumentGenerator:
161
- """Gerencia a geração de documentos usando um modelo público"""
162
 
163
  def __init__(self):
164
- # Usando um Space público de geração de texto
165
- self.client = Client("abidlabs/gpt4all") # Space público e estável
166
  self.prompt_manager = PromptManager()
167
- self.max_retries = 3
168
 
169
  def generate(self, doc_type: str, context: Dict[str, str]) -> str:
170
  """Gera o documento baseado no tipo e contexto"""
171
- for attempt in range(self.max_retries):
172
- try:
173
- prompt = self.prompt_manager.get_base_prompt(doc_type, context)
174
-
175
- # Configuração específica para o GPT4All
176
- result = self.client.predict(
177
- prompt, # Prompt para geração
178
- "portuguese", # Idioma
179
- 0.7, # Temperatura
180
- 1024, # Tamanho máximo
181
- api_name="/predict"
182
- )
183
-
184
- return self._format_output(result)
185
-
186
- except Exception as e:
187
- error_msg = str(e)
188
- logger.error(f"Tentativa {attempt + 1} falhou: {error_msg}")
189
-
190
- if attempt < self.max_retries - 1:
191
- continue
192
- else:
193
- if "quota" in error_msg.lower():
194
- return "Serviço temporariamente indisponível. Por favor, tente novamente em alguns minutos."
195
- elif "timeout" in error_msg.lower():
196
- return "O servidor está demorando para responder. Por favor, tente novamente."
197
- else:
198
- return "Não foi possível gerar o documento. Por favor, tente novamente mais tarde."
199
 
200
  def _format_output(self, text: str) -> str:
201
  """Formata o texto gerado para melhor apresentação"""
202
- if not isinstance(text, str):
203
- if isinstance(text, (list, tuple)) and len(text) > 0:
204
- text = str(text[0])
205
- else:
206
- text = str(text)
207
  return text.strip()
208
 
209
  class WebInterface:
@@ -219,7 +137,7 @@ class WebInterface:
219
  with gr.Blocks(theme=gr.themes.Soft()) as self.app:
220
  gr.Markdown("""
221
  # Gerador de Documentos Criminais
222
- ### Powered by AI Technology
223
  """)
224
 
225
  with gr.Row():
@@ -229,10 +147,7 @@ class WebInterface:
229
  choices=[
230
  "Habeas Corpus",
231
  "Denúncia",
232
- "Alegações Finais",
233
- "Resposta à Acusação",
234
- "Recurso em Sentido Estrito",
235
- "Apelação Criminal"
236
  ],
237
  label="Tipo de Documento",
238
  value="Habeas Corpus"
@@ -361,9 +276,8 @@ class WebInterface:
361
  self.app.launch(share=True)
362
 
363
  if __name__ == "__main__":
364
- # Arquivo requirements.txt necessário:
365
- # gradio==4.19.2
366
- # gradio_client==0.10.1
367
 
368
  interface = WebInterface()
369
  interface.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
  import json
4
  from datetime import datetime
 
 
5
  import logging
6
+ from typing import Dict, List, Optional
7
 
8
  # Configuração do logging
9
  logging.basicConfig(
 
87
  3. Mérito
88
  4. Análise das provas
89
  5. Pedidos
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  """
91
  }
92
 
93
  return prompts.get(doc_type, "Tipo de documento não suportado")
94
 
95
  class DocumentGenerator:
96
+ """Gerencia a geração de documentos usando GPT4All-J"""
97
 
98
  def __init__(self):
99
+ self.pipe = pipeline("text-generation", model="nomic-ai/gpt4all-j")
 
100
  self.prompt_manager = PromptManager()
 
101
 
102
  def generate(self, doc_type: str, context: Dict[str, str]) -> str:
103
  """Gera o documento baseado no tipo e contexto"""
104
+ try:
105
+ prompt = self.prompt_manager.get_base_prompt(doc_type, context)
106
+
107
+ # Configuração para a geração
108
+ result = self.pipe(
109
+ prompt,
110
+ max_length=2048,
111
+ temperature=0.7,
112
+ top_p=0.95,
113
+ num_return_sequences=1,
114
+ do_sample=True
115
+ )[0]['generated_text']
116
+
117
+ return self._format_output(result)
118
+
119
+ except Exception as e:
120
+ logger.error(f"Erro na geração: {str(e)}")
121
+ return f"Erro na geração do documento: {str(e)}"
 
 
 
 
 
 
 
 
 
 
122
 
123
  def _format_output(self, text: str) -> str:
124
  """Formata o texto gerado para melhor apresentação"""
 
 
 
 
 
125
  return text.strip()
126
 
127
  class WebInterface:
 
137
  with gr.Blocks(theme=gr.themes.Soft()) as self.app:
138
  gr.Markdown("""
139
  # Gerador de Documentos Criminais
140
+ ### Powered by GPT4All-J
141
  """)
142
 
143
  with gr.Row():
 
147
  choices=[
148
  "Habeas Corpus",
149
  "Denúncia",
150
+ "Alegações Finais"
 
 
 
151
  ],
152
  label="Tipo de Documento",
153
  value="Habeas Corpus"
 
276
  self.app.launch(share=True)
277
 
278
  if __name__ == "__main__":
279
+ # Dependências necessárias:
280
+ # pip install gradio transformers torch
 
281
 
282
  interface = WebInterface()
283
  interface.launch()