DHEIVER commited on
Commit
99c1a44
·
verified ·
1 Parent(s): 428cd1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -48
app.py CHANGED
@@ -10,56 +10,51 @@ logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
  class DocumentGenerator:
13
- """Gerencia a geração de documentos usando LLM"""
14
 
15
  def __init__(self):
16
- # Usa a API key do ambiente
17
- self.api = HfApi(token=os.environ.get("HF_TOKEN"))
18
- # Usa modelo otimizado para português
19
- self.model = "NeuralBeagle14-7B"
 
20
 
21
  def generate(self, doc_type: str, context: Dict[str, str]) -> str:
22
- """Gera o documento usando LLM"""
23
  try:
24
- base_prompt = f"""Atue como um advogado criminalista brasileiro experiente.
25
- Você deve gerar uma peça processual do tipo {doc_type} em português, formato jurídico brasileiro.
26
-
27
- DADOS:
28
- - Cliente: {context.get('client_name')}
29
- - Processo: {context.get('process_number')}
30
- - Tribunal: {context.get('court')}
31
- - Comarca: {context.get('jurisdiction')}
32
-
33
- FATOS:
34
- {context.get('facts')}
35
-
36
- FUNDAMENTOS JURÍDICOS:
37
- {context.get('legal_basis')}
38
-
39
- INSTRUÇÕES ESPECÍFICAS:
40
- 1. Use linguagem jurídica formal
41
- 2. Siga estritamente o formato de peças processuais brasileiras
42
- 3. Mantenha a estrutura com endereçamento, qualificação, fatos, direito e pedidos
43
- 4. Inclua local e data ao final
44
- 5. Use apenas os dados fornecidos
45
- 6. Evite repetições desnecessárias
46
- 7. Cite corretamente artigos e jurisprudência
47
- 8. Use formatação profissional
48
-
49
- COMECE A GERAR O DOCUMENTO AGORA:"""
50
 
51
- # Faz a chamada à API
52
- inference = InferenceApi(repo_id=f"meta-llama/{self.model}", token=os.environ.get("HF_TOKEN"))
53
- response = inference(
54
- base_prompt,
55
- max_length=4096,
56
- temperature=0.3,
57
- top_p=0.95,
58
- repetition_penalty=1.15,
59
- do_sample=True
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  )
61
 
62
- return self._format_output(response[0]['generated_text'])
63
 
64
  except Exception as e:
65
  logger.error(f"Erro na geração: {str(e)}")
@@ -69,18 +64,17 @@ class DocumentGenerator:
69
  """Formata o texto gerado"""
70
  if not text:
71
  return "Erro: Nenhum texto gerado"
72
-
73
  # Remove o prompt da resposta
74
- text = text.split("COMECE A GERAR O DOCUMENTO AGORA:")[-1].strip()
75
 
76
  # Ajusta formatação
77
  lines = [line.strip() for line in text.split('\n') if line.strip()]
78
  formatted_text = '\n\n'.join(lines)
79
 
80
- # Adiciona data se não existir
81
- if "[DATA]" in formatted_text:
82
- current_date = datetime.now().strftime('%d de %B de %Y')
83
- formatted_text = formatted_text.replace("[DATA]", current_date)
84
 
85
  return formatted_text
86
 
 
10
  logger = logging.getLogger(__name__)
11
 
12
  class DocumentGenerator:
13
+ """Gerencia a geração de documentos usando modelo público"""
14
 
15
  def __init__(self):
16
+ # Usando um Space público que está efetivamente disponível
17
+ self.client = InferenceApi(
18
+ repo_id="OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5",
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"""You are a Brazilian criminal lawyer. Create a {doc_type} in Portuguese following Brazilian legal standards.
26
+
27
+ Information:
28
+ Client: {context.get('client_name')}
29
+ Process: {context.get('process_number')}
30
+ Court: {context.get('court')}
31
+ Jurisdiction: {context.get('jurisdiction')}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ Facts:
34
+ {context.get('facts')}
35
+
36
+ Legal Basis:
37
+ {context.get('legal_basis')}
38
+
39
+ Instructions:
40
+ 1. Use formal legal Portuguese
41
+ 2. Follow Brazilian legal document format
42
+ 3. Include all required sections
43
+ 4. Be precise and clear
44
+ 5. Keep proper legal formatting"""
45
+
46
+ response = self.client(
47
+ inputs=prompt,
48
+ parameters={
49
+ "max_new_tokens": 2048,
50
+ "temperature": 0.3,
51
+ "top_p": 0.95,
52
+ "repetition_penalty": 1.15,
53
+ "do_sample": True
54
+ }
55
  )
56
 
57
+ return self._format_output(response[0]["generated_text"])
58
 
59
  except Exception as e:
60
  logger.error(f"Erro na geração: {str(e)}")
 
64
  """Formata o texto gerado"""
65
  if not text:
66
  return "Erro: Nenhum texto gerado"
67
+
68
  # Remove o prompt da resposta
69
+ text = text.split("Instructions:")[-1].strip()
70
 
71
  # Ajusta formatação
72
  lines = [line.strip() for line in text.split('\n') if line.strip()]
73
  formatted_text = '\n\n'.join(lines)
74
 
75
+ # Adiciona data atual
76
+ current_date = datetime.now().strftime('%d de %B de %Y')
77
+ formatted_text = f"{formatted_text}\n\n{context.get('jurisdiction')}, {current_date}"
 
78
 
79
  return formatted_text
80