Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -5,9 +5,8 @@ from PIL import Image
|
|
| 5 |
from io import BytesIO
|
| 6 |
import replicate
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
from openai import OpenAI
|
| 11 |
|
| 12 |
# Page configuration must be the first Streamlit command
|
| 13 |
st.set_page_config(page_title="CuentAI – AI Story Maker", layout="wide")
|
|
@@ -19,6 +18,80 @@ load_dotenv()
|
|
| 19 |
replicate_token = os.getenv("REPLICATE_API_TOKEN")
|
| 20 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# Optional TTS setup
|
| 23 |
# Uncomment if using Google Cloud TTS
|
| 24 |
# from google.cloud import texttospeech
|
|
@@ -56,16 +129,20 @@ def generate_story(name: str, theme: str) -> str:
|
|
| 56 |
# Format the prompt with user inputs
|
| 57 |
prompt = prompt_template.format(name=name, theme=theme)
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
try:
|
| 60 |
-
# Usar
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
max_tokens=600,
|
| 67 |
-
)
|
| 68 |
-
return response.choices[0].message.content.strip()
|
| 69 |
except Exception as e:
|
| 70 |
st.error(f"Error generating story: {e}")
|
| 71 |
# Return a fallback story for demo purposes
|
|
@@ -136,14 +213,12 @@ def generate_image_dalle(prompt: str, protagonist: str) -> str:
|
|
| 136 |
)
|
| 137 |
|
| 138 |
try:
|
| 139 |
-
# Usar
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
)
|
| 146 |
-
return response.data[0].url
|
| 147 |
except Exception as e:
|
| 148 |
st.error(f"Error generating image: {e}")
|
| 149 |
# Return a placeholder image URL
|
|
|
|
| 5 |
from io import BytesIO
|
| 6 |
import replicate
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
+
import json
|
| 9 |
+
import time
|
|
|
|
| 10 |
|
| 11 |
# Page configuration must be the first Streamlit command
|
| 12 |
st.set_page_config(page_title="CuentAI – AI Story Maker", layout="wide")
|
|
|
|
| 18 |
replicate_token = os.getenv("REPLICATE_API_TOKEN")
|
| 19 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 20 |
|
| 21 |
+
# Funciones para comunicarse con OpenAI directamente a través de requests en lugar de usar el SDK
|
| 22 |
+
def openai_chat_completion(prompt, model="gpt-4-turbo-preview", temperature=0.8, max_tokens=600):
|
| 23 |
+
"""Usa la API de OpenAI directamente a través de requests para evitar problemas con el SDK"""
|
| 24 |
+
|
| 25 |
+
# Mostrar información para debugging
|
| 26 |
+
st.info(f"Usando clave de API: {openai_api_key[:5]}...{openai_api_key[-4:]}")
|
| 27 |
+
|
| 28 |
+
headers = {
|
| 29 |
+
"Content-Type": "application/json",
|
| 30 |
+
"Authorization": f"Bearer {openai_api_key}"
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
payload = {
|
| 34 |
+
"model": model,
|
| 35 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 36 |
+
"temperature": float(temperature),
|
| 37 |
+
"max_tokens": int(max_tokens)
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
# Imprimir información para depuración
|
| 42 |
+
st.write("Enviando solicitud a OpenAI...")
|
| 43 |
+
|
| 44 |
+
# Imprimir payload para depuración (solo durante desarrollo)
|
| 45 |
+
st.json(payload)
|
| 46 |
+
|
| 47 |
+
response = requests.post(
|
| 48 |
+
"https://api.openai.com/v1/chat/completions",
|
| 49 |
+
headers=headers,
|
| 50 |
+
json=payload,
|
| 51 |
+
timeout=60 # Aumentar timeout para evitar errores por tiempo
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
st.write(f"Estado de respuesta: {response.status_code}")
|
| 55 |
+
|
| 56 |
+
# Si hay un error, mostrar el detalle
|
| 57 |
+
if response.status_code != 200:
|
| 58 |
+
st.error(f"Error de API: {response.status_code} - {response.text}")
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
response_data = response.json()
|
| 62 |
+
st.success("Respuesta recibida correctamente")
|
| 63 |
+
return response_data["choices"][0]["message"]["content"]
|
| 64 |
+
except Exception as e:
|
| 65 |
+
st.error(f"Error con la API de OpenAI: {str(e)}")
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
def openai_generate_image(prompt):
|
| 69 |
+
"""Genera imágenes con DALL-E 3 directamente a través de requests"""
|
| 70 |
+
headers = {
|
| 71 |
+
"Content-Type": "application/json",
|
| 72 |
+
"Authorization": f"Bearer {openai_api_key}"
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
payload = {
|
| 76 |
+
"model": "dall-e-3",
|
| 77 |
+
"prompt": prompt,
|
| 78 |
+
"n": 1,
|
| 79 |
+
"size": "1024x1024",
|
| 80 |
+
"quality": "standard"
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
response = requests.post(
|
| 85 |
+
"https://api.openai.com/v1/images/generations",
|
| 86 |
+
headers=headers,
|
| 87 |
+
json=payload
|
| 88 |
+
)
|
| 89 |
+
response.raise_for_status()
|
| 90 |
+
return response.json()["data"][0]["url"]
|
| 91 |
+
except Exception as e:
|
| 92 |
+
st.error(f"Error generando imagen: {e}")
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
# Optional TTS setup
|
| 96 |
# Uncomment if using Google Cloud TTS
|
| 97 |
# from google.cloud import texttospeech
|
|
|
|
| 129 |
# Format the prompt with user inputs
|
| 130 |
prompt = prompt_template.format(name=name, theme=theme)
|
| 131 |
|
| 132 |
+
# Mostrar mensaje de carga
|
| 133 |
+
with st.spinner("Generando tu historia personalizada..."):
|
| 134 |
+
# Información de depuración
|
| 135 |
+
st.write("Datos de entrada:")
|
| 136 |
+
st.write(f"- Protagonista: {name}")
|
| 137 |
+
st.write(f"- Tema: {theme}")
|
| 138 |
+
|
| 139 |
try:
|
| 140 |
+
# Usar nuestra función personalizada que se comunica directamente con la API
|
| 141 |
+
story = openai_chat_completion(prompt)
|
| 142 |
+
if story:
|
| 143 |
+
return story.strip()
|
| 144 |
+
else:
|
| 145 |
+
raise Exception("No se pudo generar la historia")
|
|
|
|
|
|
|
|
|
|
| 146 |
except Exception as e:
|
| 147 |
st.error(f"Error generating story: {e}")
|
| 148 |
# Return a fallback story for demo purposes
|
|
|
|
| 213 |
)
|
| 214 |
|
| 215 |
try:
|
| 216 |
+
# Usar nuestra función personalizada que se comunica directamente con la API
|
| 217 |
+
image_url = openai_generate_image(full_prompt)
|
| 218 |
+
if image_url:
|
| 219 |
+
return image_url
|
| 220 |
+
else:
|
| 221 |
+
raise Exception("No se pudo generar la imagen")
|
|
|
|
|
|
|
| 222 |
except Exception as e:
|
| 223 |
st.error(f"Error generating image: {e}")
|
| 224 |
# Return a placeholder image URL
|