Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,74 +2,38 @@ from dotenv import load_dotenv
|
|
2 |
import streamlit as st
|
3 |
import os
|
4 |
import google.generativeai as genai
|
5 |
-
from PIL import Image
|
6 |
|
7 |
load_dotenv()
|
8 |
|
9 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
10 |
|
11 |
-
#
|
12 |
-
def get_gemini_response(
|
13 |
-
model = genai.GenerativeModel(
|
14 |
-
# If both image and text are provided
|
15 |
-
if image_data and input_prompt:
|
16 |
-
full_prompt = f"""
|
17 |
-
You are a famous creative writer. Look at the image provided and also consider the following prompt: "{input_prompt}".
|
18 |
-
Create a {length} {genre} in {language}. The {genre} should be {mood}, based on both the image and the prompt, and contain realistic and emotional elements.
|
19 |
-
"""
|
20 |
-
response = model.generate_content([full_prompt, image_data[0]])
|
21 |
-
|
22 |
-
# If only image is provided
|
23 |
-
elif image_data:
|
24 |
-
full_prompt = f"""
|
25 |
-
You are a famous creative writer. Look at the image provided and create a {length} {genre} in {language}.
|
26 |
-
The {genre} should be {mood}. The {genre} should be based on the image and contain realistic and emotional elements.
|
27 |
-
"""
|
28 |
-
response = model.generate_content([full_prompt, image_data[0]])
|
29 |
-
|
30 |
-
# If only text is provided
|
31 |
-
elif input_prompt:
|
32 |
-
full_prompt = f"""
|
33 |
-
You are a creative writer. Create a {length} {genre} in {language}. The {genre} should be {mood}. The {genre} should be based on the following prompt:
|
34 |
-
|
35 |
-
"{input_prompt}"
|
36 |
-
|
37 |
-
Make sure it contains realistic and emotional elements.
|
38 |
-
"""
|
39 |
-
response = model.generate_content([full_prompt])
|
40 |
|
41 |
-
#
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
44 |
|
45 |
-
|
|
|
|
|
46 |
if response and response.parts:
|
47 |
return response.parts[0].text
|
48 |
else:
|
49 |
-
raise ValueError("
|
50 |
-
|
51 |
-
# Function to setup uploaded image
|
52 |
-
def input_image_setup(uploaded_file):
|
53 |
-
if uploaded_file is not None:
|
54 |
-
bytes_data = uploaded_file.getvalue()
|
55 |
-
image_parts = [
|
56 |
-
{
|
57 |
-
"mime_type": uploaded_file.type,
|
58 |
-
"data": bytes_data
|
59 |
-
}
|
60 |
-
]
|
61 |
-
return image_parts
|
62 |
-
else:
|
63 |
-
return None
|
64 |
|
65 |
-
#
|
66 |
-
st.set_page_config(page_title="Poetic Vision", page_icon=":pencil:", layout="wide") #
|
67 |
|
68 |
-
#
|
69 |
st.markdown("<h1 style='text-align: center;'>VisionTales</h1>", unsafe_allow_html=True)
|
70 |
st.markdown("<h3 style='text-align: center;'>Convierte tus ideas en historias inolvidables.</h3>", unsafe_allow_html=True)
|
71 |
|
72 |
-
#
|
73 |
st.markdown("""
|
74 |
<style>
|
75 |
div.stButton > button {
|
@@ -92,38 +56,32 @@ st.markdown("""
|
|
92 |
</style>
|
93 |
""", unsafe_allow_html=True)
|
94 |
|
95 |
-
#
|
96 |
-
col1, col2 = st.columns([2, 3]) # 2 + 3 = 5
|
97 |
|
98 |
with col1:
|
99 |
-
#
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
|
110 |
-
#
|
111 |
submit = st.button("Escribir mi historia")
|
112 |
|
113 |
-
#
|
114 |
-
if uploaded_file is not None:
|
115 |
-
image = Image.open(uploaded_file)
|
116 |
-
col1.image(image, caption="Imagen subida", use_column_width=True)
|
117 |
-
|
118 |
-
# Handling the button click
|
119 |
if submit:
|
120 |
-
if
|
121 |
try:
|
122 |
-
|
123 |
-
response = get_gemini_response(input_prompt, image_data, genre, length, language, mood)
|
124 |
col2.subheader("Contenido generado:")
|
125 |
col2.write(response)
|
126 |
except ValueError as e:
|
127 |
col2.error(f"Error: {str(e)}")
|
128 |
else:
|
129 |
-
col2.error("Por favor,
|
|
|
2 |
import streamlit as st
|
3 |
import os
|
4 |
import google.generativeai as genai
|
|
|
5 |
|
6 |
load_dotenv()
|
7 |
|
8 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
9 |
|
10 |
+
# Función para obtener respuesta del modelo Gemini
|
11 |
+
def get_gemini_response(target_audience, product, text_type, length, language, mood, model_choice):
|
12 |
+
model = genai.GenerativeModel(model_choice)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
# Crear el prompt completo basado en los campos del frontend
|
15 |
+
full_prompt = f"""
|
16 |
+
Eres un escritor creativo famoso. Crea un {length} {text_type} en {language}.
|
17 |
+
El {text_type} debe ser {mood}, dirigido a este público objetivo: {target_audience}, y relacionado con el producto: "{product}".
|
18 |
+
Asegúrate de que contenga elementos realistas y emocionales.
|
19 |
+
"""
|
20 |
|
21 |
+
response = model.generate_content([full_prompt])
|
22 |
+
|
23 |
+
# Comprobar si la respuesta es válida y devolver el texto
|
24 |
if response and response.parts:
|
25 |
return response.parts[0].text
|
26 |
else:
|
27 |
+
raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
+
# Inicializar la aplicación Streamlit
|
30 |
+
st.set_page_config(page_title="Poetic Vision", page_icon=":pencil:", layout="wide") # Configurar el diseño en ancho
|
31 |
|
32 |
+
# Componentes principales de la UI
|
33 |
st.markdown("<h1 style='text-align: center;'>VisionTales</h1>", unsafe_allow_html=True)
|
34 |
st.markdown("<h3 style='text-align: center;'>Convierte tus ideas en historias inolvidables.</h3>", unsafe_allow_html=True)
|
35 |
|
36 |
+
# Añadir CSS personalizado para el botón
|
37 |
st.markdown("""
|
38 |
<style>
|
39 |
div.stButton > button {
|
|
|
56 |
</style>
|
57 |
""", unsafe_allow_html=True)
|
58 |
|
59 |
+
# Crear dos columnas para el diseño (40% y 60%)
|
60 |
+
col1, col2 = st.columns([2, 3]) # 2 + 3 = 5 partes en total
|
61 |
|
62 |
with col1:
|
63 |
+
# Entradas del usuario
|
64 |
+
target_audience = st.text_input("Público objetivo:", placeholder="Especifica tu público aquí...")
|
65 |
+
product = st.text_input("Producto:", placeholder="Especifica el producto aquí...")
|
66 |
+
text_type = st.selectbox("Tipo de texto:", ["Historia", "Shayari", "Sher", "Poema", "Cita"])
|
67 |
+
length = st.selectbox("Longitud del texto:", ["Corto", "Largo"])
|
68 |
+
language = st.selectbox("Idioma del texto:", ["Español", "Inglés"])
|
69 |
+
mood = st.selectbox("Tono del Texto:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
|
70 |
+
|
71 |
+
# Opción para seleccionar el modelo
|
72 |
+
model_choice = st.selectbox("Selecciona el modelo:", ["gemini-1.5-flash", "gemini-1.5-pro"], index=0)
|
73 |
|
74 |
+
# Botón para generar contenido
|
75 |
submit = st.button("Escribir mi historia")
|
76 |
|
77 |
+
# Manejo del clic en el botón
|
|
|
|
|
|
|
|
|
|
|
78 |
if submit:
|
79 |
+
if target_audience and product: # Verificar que se haya proporcionado el público objetivo y el producto
|
80 |
try:
|
81 |
+
response = get_gemini_response(target_audience, product, text_type, length, language, mood, model_choice)
|
|
|
82 |
col2.subheader("Contenido generado:")
|
83 |
col2.write(response)
|
84 |
except ValueError as e:
|
85 |
col2.error(f"Error: {str(e)}")
|
86 |
else:
|
87 |
+
col2.error("Por favor, proporciona el público objetivo y el producto.")
|