Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,160 +1,43 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
from docx import Document
|
| 3 |
import tempfile
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
-
import requests
|
| 7 |
-
import json
|
| 8 |
-
import traceback
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
# Add custom CSS
|
| 14 |
-
st.markdown("""
|
| 15 |
-
<style>
|
| 16 |
-
.main {
|
| 17 |
-
background-color: #f5f5f5;
|
| 18 |
-
}
|
| 19 |
-
.stApp {
|
| 20 |
-
max-width: 1200px;
|
| 21 |
-
margin: 0 auto;
|
| 22 |
-
}
|
| 23 |
-
h1 {
|
| 24 |
-
color: #2c3e50;
|
| 25 |
-
}
|
| 26 |
-
.debug-info {
|
| 27 |
-
background-color: #f0f0f0;
|
| 28 |
-
padding: 10px;
|
| 29 |
-
border-radius: 5px;
|
| 30 |
-
font-family: monospace;
|
| 31 |
-
margin-top: 20px;
|
| 32 |
-
}
|
| 33 |
-
</style>
|
| 34 |
-
""", unsafe_allow_html=True)
|
| 35 |
-
|
| 36 |
-
# Initialize session state for debugging
|
| 37 |
-
if "debug_info" not in st.session_state:
|
| 38 |
-
st.session_state["debug_info"] = ""
|
| 39 |
-
|
| 40 |
-
# Initialize with simpler, more reliable models
|
| 41 |
-
AVAILABLE_MODELS = {
|
| 42 |
-
"GPT-2 (estable)": "distilgpt2",
|
| 43 |
-
"Flan-T5 (recomendado)": "google/flan-t5-small",
|
| 44 |
-
"BLOOM (espa帽ol)": "bigscience/bloom-560m",
|
| 45 |
-
"XLM-RoBERTa": "xlm-roberta-base"
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
# Default model
|
| 49 |
-
DEFAULT_MODEL = "google/flan-t5-small"
|
| 50 |
|
| 51 |
# Function to format the prompt for Rorschach interpretation
|
| 52 |
def format_prompt(message, history):
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
return prompt
|
| 58 |
|
| 59 |
-
# Function to generate response
|
| 60 |
-
def generate(prompt, history, temperature=0.
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
result = generator(formatted_prompt,
|
| 81 |
-
max_length=len(formatted_prompt.split()) + max_new_tokens,
|
| 82 |
-
temperature=temperature,
|
| 83 |
-
top_p=top_p,
|
| 84 |
-
repetition_penalty=repetition_penalty,
|
| 85 |
-
do_sample=True)
|
| 86 |
-
|
| 87 |
-
# Get the generated text
|
| 88 |
-
generated_text = result[0]['generated_text']
|
| 89 |
-
new_content = generated_text[len(formatted_prompt):].strip()
|
| 90 |
-
|
| 91 |
-
return new_content if new_content else "An谩lisis: La respuesta sugiere elementos de personalidad interesantes, pero se requiere m谩s contexto para una evaluaci贸n completa."
|
| 92 |
-
|
| 93 |
-
except (ImportError, Exception) as e:
|
| 94 |
-
# If transformers approach fails, fall back to API
|
| 95 |
-
if debug_mode:
|
| 96 |
-
st.session_state["debug_info"] += f"\nError con transformers: {str(e)}\nProbando API directa..."
|
| 97 |
-
|
| 98 |
-
# Option 2: Try Hugging Face Inference API with minimal parameters
|
| 99 |
-
api_url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 100 |
-
|
| 101 |
-
# Simplify the payload to bare minimum
|
| 102 |
-
if "t5" in model_id.lower():
|
| 103 |
-
# For T5 models
|
| 104 |
-
payload = {"inputs": "Interpret the following Rorschach test response: " + prompt}
|
| 105 |
-
else:
|
| 106 |
-
# For other models
|
| 107 |
-
payload = {"inputs": formatted_prompt}
|
| 108 |
-
|
| 109 |
-
# Make direct API call
|
| 110 |
-
headers = {} # No auth token needed for public models
|
| 111 |
-
response = requests.post(api_url, headers=headers, json=payload)
|
| 112 |
-
|
| 113 |
-
# Debug response
|
| 114 |
-
if debug_mode:
|
| 115 |
-
st.session_state["debug_info"] += f"\nAPI Status: {response.status_code}\nResponse: {response.text[:200]}"
|
| 116 |
-
|
| 117 |
-
# Handle API response
|
| 118 |
-
if response.status_code == 200:
|
| 119 |
-
# Try to parse JSON response
|
| 120 |
-
result = response.json()
|
| 121 |
-
|
| 122 |
-
# Handle different response formats
|
| 123 |
-
if isinstance(result, list) and len(result) > 0:
|
| 124 |
-
if isinstance(result[0], dict) and "generated_text" in result[0]:
|
| 125 |
-
# Standard format for text generation
|
| 126 |
-
generated_text = result[0]["generated_text"]
|
| 127 |
-
new_content = generated_text[len(formatted_prompt):].strip() if formatted_prompt in generated_text else generated_text
|
| 128 |
-
return new_content
|
| 129 |
-
else:
|
| 130 |
-
# Direct text in list
|
| 131 |
-
return str(result[0])
|
| 132 |
-
else:
|
| 133 |
-
# Other formats
|
| 134 |
-
return str(result)
|
| 135 |
-
else:
|
| 136 |
-
# Use a simpler fallback approach
|
| 137 |
-
return """
|
| 138 |
-
An谩lisis psicol贸gico de la respuesta al Test de Rorschach:
|
| 139 |
-
|
| 140 |
-
La descripci贸n proporcionada sugiere aspectos interesantes sobre la personalidad del sujeto. Se observan elementos que indican una tendencia hacia el pensamiento creativo y una capacidad para ver patrones complejos. La interpretaci贸n detallada requerir铆a una evaluaci贸n profesional completa, pero los elementos descritos pueden indicar una personalidad con sensibilidad hacia los detalles y una imaginaci贸n activa.
|
| 141 |
-
|
| 142 |
-
Nota: Esta es una interpretaci贸n generada como ejemplo debido a limitaciones t茅cnicas temporales con la API.
|
| 143 |
-
"""
|
| 144 |
-
|
| 145 |
-
except Exception as e:
|
| 146 |
-
error_traceback = traceback.format_exc()
|
| 147 |
-
if debug_mode:
|
| 148 |
-
st.session_state["debug_info"] += f"\n\nExcepci贸n: {str(e)}\n{error_traceback}"
|
| 149 |
-
|
| 150 |
-
# Return a generic interpretation as fallback
|
| 151 |
-
return """
|
| 152 |
-
An谩lisis psicol贸gico (generado localmente):
|
| 153 |
-
|
| 154 |
-
Las respuestas al Test de Rorschach revelan patrones interesantes en la forma de procesar informaci贸n visual. La interpretaci贸n sugiere una personalidad con capacidad para la asociaci贸n libre y pensamiento abstracto. Los elementos descritos podr铆an indicar creatividad y sensibilidad emocional.
|
| 155 |
-
|
| 156 |
-
Nota: Esta es una interpretaci贸n b谩sica generada localmente debido a un problema t茅cnico.
|
| 157 |
-
"""
|
| 158 |
|
| 159 |
# Function to replace variables in a Word template
|
| 160 |
def replace_variables_word(doc, variables):
|
|
@@ -162,7 +45,6 @@ def replace_variables_word(doc, variables):
|
|
| 162 |
for key, value in variables.items():
|
| 163 |
if f'<{key}>' in paragraph.text:
|
| 164 |
paragraph.text = re.sub(f'<{key}>', value, paragraph.text)
|
| 165 |
-
|
| 166 |
for table in doc.tables:
|
| 167 |
for row in table.rows:
|
| 168 |
for cell in row.cells:
|
|
@@ -173,149 +55,46 @@ def replace_variables_word(doc, variables):
|
|
| 173 |
|
| 174 |
# Function to generate a Word document with interpretation
|
| 175 |
def generate_word_document(interpretation):
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
doc = Document()
|
| 182 |
-
doc.add_heading('Interpretaci贸n del Test de Rorschach', 0)
|
| 183 |
-
doc.add_paragraph(interpretation)
|
| 184 |
-
else:
|
| 185 |
-
doc = Document(template_path)
|
| 186 |
-
variables = {'INTERPRETACION': interpretation}
|
| 187 |
-
replace_variables_word(doc, variables)
|
| 188 |
-
|
| 189 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as tmp:
|
| 190 |
-
doc.save(tmp.name)
|
| 191 |
-
return tmp.name
|
| 192 |
-
except Exception as e:
|
| 193 |
-
st.error(f"Error generando documento: {str(e)}")
|
| 194 |
-
return None
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
"python-docx>=0.8.11",
|
| 200 |
-
"requests>=2.28.0",
|
| 201 |
-
"transformers>=4.34.0",
|
| 202 |
-
]
|
| 203 |
|
| 204 |
-
#
|
| 205 |
st.title("Interpretaci贸n del Test de Rorschach")
|
| 206 |
-
st.markdown("""
|
| 207 |
-
Esta aplicaci贸n genera interpretaciones psicol贸gicas basadas en las descripciones de lo que ves en las manchas del Test de Rorschach.
|
| 208 |
-
""")
|
| 209 |
-
|
| 210 |
-
# Add notice about fallback mode
|
| 211 |
-
st.info("Si la API externa falla, la aplicaci贸n seguir谩 funcionando en modo local o mostrar谩 una interpretaci贸n predeterminada.", icon="鈩癸笍")
|
| 212 |
-
|
| 213 |
-
# Sidebar for settings
|
| 214 |
-
with st.sidebar:
|
| 215 |
-
st.header("Configuraci贸n")
|
| 216 |
-
|
| 217 |
-
# Install dependencies button
|
| 218 |
-
if st.button("馃摝 Instalar dependencias"):
|
| 219 |
-
try:
|
| 220 |
-
import subprocess
|
| 221 |
-
for req in REQUIREMENTS:
|
| 222 |
-
subprocess.check_call(["pip", "install", req])
|
| 223 |
-
st.success("隆Dependencias instaladas correctamente!")
|
| 224 |
-
except Exception as e:
|
| 225 |
-
st.error(f"Error instalando dependencias: {str(e)}")
|
| 226 |
-
|
| 227 |
-
# Model selection
|
| 228 |
-
selected_model = st.selectbox(
|
| 229 |
-
"Seleccionar modelo:",
|
| 230 |
-
list(AVAILABLE_MODELS.keys()),
|
| 231 |
-
index=1 # Default to Flan-T5
|
| 232 |
-
)
|
| 233 |
-
|
| 234 |
-
# Temperature setting (creativity)
|
| 235 |
-
temperature = st.slider(
|
| 236 |
-
"Temperatura (creatividad):",
|
| 237 |
-
min_value=0.1,
|
| 238 |
-
max_value=1.0,
|
| 239 |
-
value=0.7,
|
| 240 |
-
step=0.1
|
| 241 |
-
)
|
| 242 |
-
|
| 243 |
-
# Max tokens
|
| 244 |
-
max_tokens = st.slider(
|
| 245 |
-
"Longitud m谩xima:",
|
| 246 |
-
min_value=50,
|
| 247 |
-
max_value=500,
|
| 248 |
-
value=200,
|
| 249 |
-
step=50
|
| 250 |
-
)
|
| 251 |
-
|
| 252 |
-
# Debug mode
|
| 253 |
-
debug_mode = st.checkbox("Modo debug", value=False)
|
| 254 |
|
| 255 |
# Chat history
|
| 256 |
if 'history' not in st.session_state:
|
| 257 |
st.session_state.history = []
|
| 258 |
|
| 259 |
-
# User input
|
| 260 |
-
entrada_usuario = st.
|
| 261 |
-
"驴Qu茅 ves en la imagen? Describe con detalle:",
|
| 262 |
-
height=100,
|
| 263 |
-
key="entrada_usuario",
|
| 264 |
-
placeholder="Por ejemplo: Veo dos personas enfrentadas, sosteniendo algo entre ellas. Tambi茅n hay formas que parecen alas en la parte superior..."
|
| 265 |
-
)
|
| 266 |
|
| 267 |
# Generate response and create Word document
|
| 268 |
-
if st.button("
|
| 269 |
if entrada_usuario:
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
model_name = selected_model
|
| 273 |
-
model_id = AVAILABLE_MODELS[selected_model]
|
| 274 |
-
|
| 275 |
-
# Generate the response
|
| 276 |
-
bot_response = generate(
|
| 277 |
-
entrada_usuario,
|
| 278 |
-
st.session_state.history,
|
| 279 |
-
temperature=temperature,
|
| 280 |
-
max_new_tokens=max_tokens
|
| 281 |
-
)
|
| 282 |
-
|
| 283 |
-
# Add to history
|
| 284 |
-
st.session_state.history.append((entrada_usuario, bot_response))
|
| 285 |
-
|
| 286 |
-
# Show the generated response
|
| 287 |
-
st.subheader("Interpretaci贸n Psicol贸gica:")
|
| 288 |
-
st.write(bot_response)
|
| 289 |
-
|
| 290 |
-
# Generate Word document
|
| 291 |
-
document_path = generate_word_document(bot_response)
|
| 292 |
-
|
| 293 |
-
if document_path:
|
| 294 |
-
# Provide download link
|
| 295 |
-
with open(document_path, "rb") as file:
|
| 296 |
-
st.download_button(
|
| 297 |
-
label="馃搫 Descargar Interpretaci贸n como Documento",
|
| 298 |
-
data=file,
|
| 299 |
-
file_name="Interpretacion_Rorschach.docx",
|
| 300 |
-
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
| 301 |
-
)
|
| 302 |
-
# Clean up the temporary file
|
| 303 |
-
try:
|
| 304 |
-
os.unlink(document_path)
|
| 305 |
-
except:
|
| 306 |
-
pass
|
| 307 |
-
else:
|
| 308 |
-
st.warning("Por favor ingresa tu descripci贸n de lo que ves en la imagen primero.")
|
| 309 |
|
| 310 |
-
#
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
|
| 315 |
# Display conversation
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
chat_text = ""
|
| 319 |
-
|
| 320 |
-
chat_text += f"T煤: {user_msg}\nBuho: {bot_msg}\n\n"
|
| 321 |
-
st.text_area("Respuestas del Buho", value=chat_text, height=300, disabled=True)
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from huggingface_hub import InferenceClient
|
| 3 |
from docx import Document
|
| 4 |
import tempfile
|
| 5 |
import os
|
| 6 |
import re
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# Initialize the client
|
| 9 |
+
client = InferenceClient("google/flan-t5-small")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
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 |
|
| 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")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
# Chat history
|
| 72 |
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)
|
|
|
|
|
|