DHEIVER commited on
Commit
7060ba3
·
verified ·
1 Parent(s): e6394a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -32
app.py CHANGED
@@ -10,48 +10,51 @@ logging.basicConfig(level=logging.INFO)
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="bigscience/bloom",
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"])
@@ -65,19 +68,19 @@ Instructions:
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
-
81
  class WebInterface:
82
  """Interface Gradio para o gerador de documentos"""
83
 
 
10
  logger = logging.getLogger(__name__)
11
 
12
  class DocumentGenerator:
13
+ """Gerencia a geração de documentos usando BERT-PT"""
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
+ [FUNDAMENTOS]
38
  {context.get('legal_basis')}
39
 
40
+ [INSTRUÇÕES]
41
+ - Use linguagem jurídica formal
42
+ - Siga formato brasileiro
43
+ - Inclua todas as seções necessárias
44
+ - Mantenha clareza e precisão
45
+ - Use formatação adequada
46
 
47
+ Gere o documento completo em português:"""
48
+
49
+ # Faz a chamada ao modelo
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
  return self._format_output(response[0]["generated_text"])
 
68
  if not text:
69
  return "Erro: Nenhum texto gerado"
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