JairoCesar commited on
Commit
82049f1
verified
1 Parent(s): 338dfa8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -49
app.py CHANGED
@@ -5,39 +5,56 @@ import tempfile
5
  import os
6
  import re
7
 
8
- # Initialize the client
9
- client = InferenceClient("Qwen/Qwen2-0.5B-Instruct")
 
10
 
11
  # Function to format the prompt for Rorschach interpretation
12
  def format_prompt(message, history):
13
- prompt = "<s>"
 
 
 
 
14
  for user_prompt, bot_response in history:
15
- prompt += f"[INST] {user_prompt} [/INST]"
16
- prompt += f" {bot_response} "
17
- prompt += f"[INST] Interpretaci贸n Rorschach: {message} [/INST]"
 
 
18
  return prompt
19
 
20
  # Function to generate response
21
  def generate(prompt, history, temperature=0.9, max_new_tokens=512, top_p=0.95, repetition_penalty=1.0):
22
- temperature = max(float(temperature), 1e-2)
23
- top_p = float(top_p)
 
24
 
25
- generate_kwargs = dict(
26
- temperature=temperature,
27
- max_new_tokens=max_new_tokens,
28
- top_p=top_p,
29
- repetition_penalty=repetition_penalty,
30
- do_sample=True,
31
- seed=42,
32
- )
33
 
34
- formatted_prompt = format_prompt(prompt, history)
35
-
36
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
37
- output = ""
38
- for response in stream:
39
- output += response.token.text
40
- return output
 
 
 
 
 
 
 
 
 
41
 
42
  # Function to replace variables in a Word template
43
  def replace_variables_word(doc, variables):
@@ -45,6 +62,7 @@ def replace_variables_word(doc, variables):
45
  for key, value in variables.items():
46
  if f'<{key}>' in paragraph.text:
47
  paragraph.text = re.sub(f'<{key}>', value, paragraph.text)
 
48
  for table in doc.tables:
49
  for row in table.rows:
50
  for cell in row.cells:
@@ -55,15 +73,25 @@ def replace_variables_word(doc, variables):
55
 
56
  # Function to generate a Word document with interpretation
57
  def generate_word_document(interpretation):
58
- template_path = os.path.join('PLANTILLAS', 'PLANTILLA_INTERPRETACION.docx')
59
- doc = Document(template_path)
60
-
61
- variables = {'INTERPRETACION': interpretation}
62
- replace_variables_word(doc, variables)
 
 
 
 
 
 
 
63
 
64
- with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as tmp:
65
- doc.save(tmp.name)
66
- return tmp.name
 
 
 
67
 
68
  # Streamlit interface
69
  st.title("Interpretaci贸n del Test de Rorschach")
@@ -73,28 +101,37 @@ if 'history' not in st.session_state:
73
  st.session_state.history = []
74
 
75
  # User input
76
- entrada_usuario = st.text_input("Que ves en las im谩genes ..:", key="entrada_usuario")
77
 
78
  # Generate response and create Word document
79
  if st.button("Enviar"):
80
  if entrada_usuario:
81
- bot_response = generate(entrada_usuario, st.session_state.history)
82
- st.session_state.history.append((entrada_usuario, bot_response))
 
83
 
84
- # Generate Word document
85
- document_path = generate_word_document(bot_response)
86
-
87
- # Provide download link
88
- with open(document_path, "rb") as file:
89
- st.download_button(
90
- label="Descargar Interpretaci贸n",
91
- data=file,
92
- file_name="Interpretacion_Rorschach.docx",
93
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
94
- )
 
 
 
 
 
 
95
 
96
  # Display conversation
97
- chat_text = ""
98
- for user_msg, bot_msg in st.session_state.history:
99
- chat_text += f"Tu: {user_msg}\nBuho: {bot_msg}\n\n"
100
- st.text_area("Respuestas del Buho", value=chat_text, height=300, disabled=False)
 
 
 
5
  import os
6
  import re
7
 
8
+ # Initialize the client with a publicly available model that doesn't require API token
9
+ # Models like facebook/opt-350m, EleutherAI/gpt-neo-125m, or bigscience/bloom-560m are good options
10
+ client = InferenceClient(model="facebook/opt-1.3b")
11
 
12
  # Function to format the prompt for Rorschach interpretation
13
  def format_prompt(message, history):
14
+ # For OPT model, we use a simpler prompt format
15
+ # Start with context about the task
16
+ prompt = "Esto es una interpretaci贸n del Test de Rorschach. "
17
+
18
+ # Add history if any
19
  for user_prompt, bot_response in history:
20
+ prompt += f"Persona: {user_prompt} Respuesta: {bot_response} "
21
+
22
+ # Add current message
23
+ prompt += f"Persona describe lo que ve en la mancha de Rorschach: {message} Interpretaci贸n psicol贸gica detallada: "
24
+
25
  return prompt
26
 
27
  # Function to generate response
28
  def generate(prompt, history, temperature=0.9, max_new_tokens=512, top_p=0.95, repetition_penalty=1.0):
29
+ try:
30
+ temperature = max(float(temperature), 1e-2)
31
+ top_p = float(top_p)
32
 
33
+ generate_kwargs = dict(
34
+ temperature=temperature,
35
+ max_new_tokens=max_new_tokens,
36
+ top_p=top_p,
37
+ repetition_penalty=repetition_penalty,
38
+ do_sample=True,
39
+ seed=42,
40
+ )
41
 
42
+ formatted_prompt = format_prompt(prompt, history)
43
+
44
+ # Simplified call to text_generation for OPT model
45
+ response = client.text_generation(
46
+ formatted_prompt,
47
+ max_new_tokens=max_new_tokens,
48
+ temperature=temperature,
49
+ top_p=top_p,
50
+ repetition_penalty=repetition_penalty,
51
+ do_sample=True
52
+ )
53
+
54
+ return response
55
+ except Exception as e:
56
+ st.error(f"Error generando respuesta: {str(e)}")
57
+ return "Lo siento, hubo un error al generar la interpretaci贸n. Por favor, intenta de nuevo."
58
 
59
  # Function to replace variables in a Word template
60
  def replace_variables_word(doc, variables):
 
62
  for key, value in variables.items():
63
  if f'<{key}>' in paragraph.text:
64
  paragraph.text = re.sub(f'<{key}>', value, paragraph.text)
65
+
66
  for table in doc.tables:
67
  for row in table.rows:
68
  for cell in row.cells:
 
73
 
74
  # Function to generate a Word document with interpretation
75
  def generate_word_document(interpretation):
76
+ try:
77
+ template_path = os.path.join('PLANTILLAS', 'PLANTILLA_INTERPRETACION.docx')
78
+ if not os.path.exists(template_path):
79
+ st.warning(f"La plantilla no se encontr贸 en: {template_path}")
80
+ # Fallback: Create a simple document without template
81
+ doc = Document()
82
+ doc.add_heading('Interpretaci贸n del Test de Rorschach', 0)
83
+ doc.add_paragraph(interpretation)
84
+ else:
85
+ doc = Document(template_path)
86
+ variables = {'INTERPRETACION': interpretation}
87
+ replace_variables_word(doc, variables)
88
 
89
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as tmp:
90
+ doc.save(tmp.name)
91
+ return tmp.name
92
+ except Exception as e:
93
+ st.error(f"Error generando documento: {str(e)}")
94
+ return None
95
 
96
  # Streamlit interface
97
  st.title("Interpretaci贸n del Test de Rorschach")
 
101
  st.session_state.history = []
102
 
103
  # User input
104
+ entrada_usuario = st.text_input("Qu茅 ves en las im谩genes:", key="entrada_usuario")
105
 
106
  # Generate response and create Word document
107
  if st.button("Enviar"):
108
  if entrada_usuario:
109
+ with st.spinner("Generando interpretaci贸n..."):
110
+ bot_response = generate(entrada_usuario, st.session_state.history)
111
+ st.session_state.history.append((entrada_usuario, bot_response))
112
 
113
+ # Generate Word document
114
+ document_path = generate_word_document(bot_response)
115
+
116
+ if document_path:
117
+ # Provide download link
118
+ with open(document_path, "rb") as file:
119
+ st.download_button(
120
+ label="Descargar Interpretaci贸n",
121
+ data=file,
122
+ file_name="Interpretacion_Rorschach.docx",
123
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
124
+ )
125
+ # Clean up the temporary file
126
+ try:
127
+ os.unlink(document_path)
128
+ except:
129
+ pass
130
 
131
  # Display conversation
132
+ if st.session_state.history:
133
+ st.subheader("Historial de Conversaci贸n")
134
+ chat_text = ""
135
+ for user_msg, bot_msg in st.session_state.history:
136
+ chat_text += f"T煤: {user_msg}\nBuho: {bot_msg}\n\n"
137
+ st.text_area("Respuestas del Buho", value=chat_text, height=300, disabled=True)