Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -37,16 +37,16 @@ st.markdown("""
|
|
| 37 |
if "debug_info" not in st.session_state:
|
| 38 |
st.session_state["debug_info"] = ""
|
| 39 |
|
| 40 |
-
# Initialize
|
| 41 |
AVAILABLE_MODELS = {
|
| 42 |
-
"GPT-2 (
|
| 43 |
-
"
|
| 44 |
-
"
|
| 45 |
-
"
|
| 46 |
}
|
| 47 |
|
| 48 |
# Default model
|
| 49 |
-
DEFAULT_MODEL = "
|
| 50 |
|
| 51 |
# Function to format the prompt for Rorschach interpretation
|
| 52 |
def format_prompt(message, history):
|
|
@@ -56,58 +56,105 @@ def format_prompt(message, history):
|
|
| 56 |
prompt += "Interpretaci贸n psicol贸gica: "
|
| 57 |
return prompt
|
| 58 |
|
| 59 |
-
# Function to generate response
|
| 60 |
def generate(prompt, history, temperature=0.7, max_new_tokens=256, top_p=0.9, repetition_penalty=1.0):
|
| 61 |
try:
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
# Use the Inference API directly with minimal parameters
|
| 65 |
-
payload = {
|
| 66 |
-
"inputs": formatted_prompt,
|
| 67 |
-
"parameters": {
|
| 68 |
-
"max_new_tokens": max_new_tokens,
|
| 69 |
-
"temperature": temperature,
|
| 70 |
-
"top_p": top_p,
|
| 71 |
-
"do_sample": True
|
| 72 |
-
}
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
# Get selected model from session state
|
| 76 |
model_id = AVAILABLE_MODELS[selected_model]
|
| 77 |
|
| 78 |
-
#
|
| 79 |
-
|
| 80 |
-
st.session_state["debug_info"] = f"Model: {model_id}\nPrompt: {formatted_prompt}"
|
| 81 |
-
|
| 82 |
-
# Direct API call using the inference endpoint
|
| 83 |
-
api_url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
| 87 |
-
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
if debug_mode:
|
| 92 |
-
st.session_state["debug_info"] += f"\
|
| 93 |
-
return f"Error en la API de Hugging Face. Por favor intenta con otro modelo o m谩s tarde."
|
| 94 |
-
|
| 95 |
-
# Extract the generated text
|
| 96 |
-
result = response.json()[0]["generated_text"]
|
| 97 |
-
|
| 98 |
-
# Remove the input prompt to get only the new content
|
| 99 |
-
new_content = result[len(formatted_prompt):]
|
| 100 |
-
|
| 101 |
-
if debug_mode:
|
| 102 |
-
st.session_state["debug_info"] += f"\n\nResponse: {new_content[:100]}..."
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
error_traceback = traceback.format_exc()
|
| 108 |
if debug_mode:
|
| 109 |
-
st.session_state["debug_info"] += f"\n\
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
# Function to replace variables in a Word template
|
| 113 |
def replace_variables_word(doc, variables):
|
|
@@ -146,19 +193,42 @@ def generate_word_document(interpretation):
|
|
| 146 |
st.error(f"Error generando documento: {str(e)}")
|
| 147 |
return None
|
| 148 |
|
| 149 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
st.title("Interpretaci贸n del Test de Rorschach")
|
| 151 |
-
st.markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# Sidebar for settings
|
| 154 |
with st.sidebar:
|
| 155 |
st.header("Configuraci贸n")
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
# Model selection
|
| 158 |
selected_model = st.selectbox(
|
| 159 |
"Seleccionar modelo:",
|
| 160 |
list(AVAILABLE_MODELS.keys()),
|
| 161 |
-
index=
|
| 162 |
)
|
| 163 |
|
| 164 |
# Temperature setting (creativity)
|
|
|
|
| 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):
|
|
|
|
| 56 |
prompt += "Interpretaci贸n psicol贸gica: "
|
| 57 |
return prompt
|
| 58 |
|
| 59 |
+
# Function to generate response using a more reliable approach
|
| 60 |
def generate(prompt, history, temperature=0.7, max_new_tokens=256, top_p=0.9, repetition_penalty=1.0):
|
| 61 |
try:
|
| 62 |
+
# Get selected model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
model_id = AVAILABLE_MODELS[selected_model]
|
| 64 |
|
| 65 |
+
# Format the prompt appropriately
|
| 66 |
+
formatted_prompt = format_prompt(prompt, history)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# Update debug info
|
| 69 |
+
if debug_mode:
|
| 70 |
+
st.session_state["debug_info"] = f"Modelo: {model_id}\nPrompt: {formatted_prompt}"
|
| 71 |
|
| 72 |
+
# Option 1: Use the transformers library directly (local inference)
|
| 73 |
+
try:
|
| 74 |
+
from transformers import pipeline
|
| 75 |
+
|
| 76 |
+
# Create a text generation pipeline
|
| 77 |
+
generator = pipeline('text-generation', model=model_id)
|
| 78 |
+
|
| 79 |
+
# Generate text
|
| 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):
|
|
|
|
| 193 |
st.error(f"Error generando documento: {str(e)}")
|
| 194 |
return None
|
| 195 |
|
| 196 |
+
# Add requirement for transformers
|
| 197 |
+
REQUIREMENTS = [
|
| 198 |
+
"streamlit>=1.28.0",
|
| 199 |
+
"python-docx>=0.8.11",
|
| 200 |
+
"requests>=2.28.0",
|
| 201 |
+
"transformers>=4.34.0",
|
| 202 |
+
]
|
| 203 |
+
|
| 204 |
+
# Display information at the top
|
| 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)
|