JeCabrera commited on
Commit
40a75f2
·
verified ·
1 Parent(s): e6dda01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -34
app.py CHANGED
@@ -2,38 +2,74 @@ from dotenv import load_dotenv
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,32 +92,38 @@ st.markdown("""
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.")
 
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
+ # Function to get response from Gemini model
12
+ def get_gemini_response(input_prompt, image_data, genre, length, language, mood):
13
+ model = genai.GenerativeModel('gemini-1.5-flash')
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
+ # If neither image nor text is provided
42
+ else:
43
+ raise ValueError("Please provide either an image or a text prompt.")
 
 
 
44
 
45
+ # Check if response is valid and return text
 
 
46
  if response and response.parts:
47
  return response.parts[0].text
48
  else:
49
+ raise ValueError("Sorry, please try a different combination of inputs.")
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
+ # Initialize Streamlit app
66
+ st.set_page_config(page_title="Poetic Vision", page_icon=":pencil:", layout="wide") # Set layout to wide
67
 
68
+ # Main UI components
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
+ # Add custom CSS for the button
73
  st.markdown("""
74
  <style>
75
  div.stButton > button {
 
92
  </style>
93
  """, unsafe_allow_html=True)
94
 
95
+ # Create two columns for layout (40% and 60%)
96
+ col1, col2 = st.columns([2, 3]) # 2 + 3 = 5 parts total
97
 
98
  with col1:
99
+ # Subir imagen primero
100
+ uploaded_file = st.file_uploader("Elegir una imagen...", type=["jpg", "jpeg", "png"])
 
 
 
 
 
 
 
 
101
 
102
+ # Agrupar opciones en un desplegable con un nuevo título
103
+ with st.expander("Clic para personalizar tu historia", expanded=False): # El desplegable está cerrado por defecto
104
+ input_prompt = st.text_input("Escribe de qué quieres que trate tu historia (opcional):", placeholder="Escribe tu mensaje aquí...")
105
+ genre = st.selectbox("Tipo de texto:", ["Historia", "Shayari", "Sher", "Poema", "Cita"])
106
+ length = st.selectbox("Longitud del texto:", ["Corto", "Largo"])
107
+ language = st.selectbox("Idioma del texto:", ["Español", "Inglés"])
108
+ mood = st.selectbox("Estado de ánimo:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
109
+
110
+ # Generate button con el nuevo estilo, centrado y ajustado
111
  submit = st.button("Escribir mi historia")
112
 
113
+ # Display uploaded image
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 uploaded_file or input_prompt:
121
  try:
122
+ image_data = input_image_setup(uploaded_file)
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, sube una imagen o proporciona un mensaje.")