JeCabrera commited on
Commit
60ce54c
·
verified ·
1 Parent(s): 1b602b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -67
app.py CHANGED
@@ -1,81 +1,129 @@
 
1
  import streamlit as st
2
- import google.generativeai as genai
3
  import os
4
- from dotenv import load_dotenv
5
- import textwrap
6
 
7
- # Cargar variables de entorno
8
  load_dotenv()
9
 
10
- # Configurar la API de Google Gemini
11
- genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
12
 
13
- # Función para formatear texto en Markdown
14
- def to_markdown(text):
15
- return textwrap.indent(text, '> ', predicate=lambda _: True)
 
 
 
 
 
 
 
16
 
17
- # Función para generar el párrafo de apertura
18
- def generate_opening_paragraph(target_audience, product, temperature, text_type, model_name):
19
- # Crear la configuración del modelo
20
- generation_config = {
21
- "temperature": temperature,
22
- "top_p": 0.95,
23
- "top_k": 62,
24
- "max_output_tokens": 2048,
25
- "response_mime_type": "text/plain",
26
- }
27
 
28
- model = genai.GenerativeModel(
29
- model_name=model_name,
30
- generation_config=generation_config,
31
- system_instruction=f"Eres un especialista en copywriting altamente capacitado, enfocado en la creación de textos persuasivos que logran captar la atención del lector, mantener su interés y llevarlo a la acción. Tienes una profunda comprensión de la psicología del consumidor, y utilizas la persuasión de manera efectiva en cada palabra que escribes, conectando con las emociones y necesidades de tu audiencia. Dominas técnicas avanzadas de redacción, como el uso de encabezados poderosos, aperturas intrigantes, llamados a la acción efectivos y storytelling cautivador. Tu habilidad para ajustar el tono y estilo al contexto asegura que cada mensaje resuene profundamente. Tienes una amplia experiencia demostrada en generar resultados de ventas tanto para negocios en línea como offline. Las respuestas deben presentarse en formato de texto, en párrafos, sin mencionar directamente el producto o servicio, ni referirse al público objetivo de manera explícita. Al responder escribe un encabezado que diga: 'Este es tu párrafo de apertura para cautivar a {target_audience}'"
32
- )
33
-
34
- chat_session = model.start_chat(
35
- history=[
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  {
37
- "role": "user",
38
- "parts": [
39
- f"Crea un párrafo de apertura para una {text_type.lower()} que haga conciente a {target_audience} que tiene un problema explicándolos con situaciones reales de su vida, utiliza un lenguaje natural o conversacional. El objetivo de este párrafo es que tengan el deseo de seguir leyendo este párrafo y saber de qué se trata {product}. Utiliza la persuasión de manera efectiva en cada palabra, dominando técnicas avanzadas como el uso de encabezados poderosos y aperturas intrigantes."
40
- "Para escribir este párrafo de apertura utiliza una o algunas de estas técnicas de Apertura para Cartas de Ventas, escoge las más adecuadas:"
41
- "1. Si.. Entonces"
42
- "2. Si / Entonces + Autoridad"
43
- "3. Honestidad"
44
- "4. Sensacionalista"
45
- "5. Haz una pregunta"
46
- "6. 'Micro aperturas'"
47
- ],
48
- },
49
  ]
50
- )
 
 
51
 
52
- response = chat_session.send_message("Genera el párrafo de apertura")
53
- return to_markdown(response.text)
54
 
55
- # Título de la aplicación
56
- st.title("Generador de Párrafos de Apertura")
 
57
 
58
- # Crear un formulario para la entrada del usuario
59
- with st.form(key='my_form'):
60
- target_audience = st.text_input("Público Objetivo", placeholder="Ejemplo: Estudiantes Universitarios")
61
- product = st.text_input("Producto", placeholder="Ejemplo: Curso de Inglés")
62
- temperature = st.slider("Creatividad", 0.0, 1.0, 0.5, 0.1)
63
- text_type = st.selectbox("Tipo de Texto", ["Página de Ventas", "Correo", "Historia"])
64
- model_selector = st.selectbox("Selecciona el modelo", ["gemini-1.5-flash", "gemini-1.5-pro"])
65
-
66
- # Botón para enviar el formulario
67
- submit_btn = st.form_submit_button("Generar Párrafo de Apertura")
68
-
69
- # Botón para limpiar el formulario (reiniciar)
70
- if st.button("Empezar de nuevo"):
71
- target_audience = ""
72
- product = ""
73
- temperature = 0.5
74
- text_type = "Página de Ventas"
75
- model_selector = "gemini-1.5-flash"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- # Mostrar el resultado
78
- if submit_btn:
79
- # Llamar a la función para generar el párrafo
80
- output_text = generate_opening_paragraph(target_audience, product, temperature, text_type, model_selector)
81
- st.markdown(output_text)
 
 
 
 
 
 
 
 
1
+ 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
+ # 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 {
76
+ background-color: #FFCC00; /* Color llamativo */
77
+ color: black; /* Texto en negro */
78
+ width: 90%;
79
+ height: 60px;
80
+ font-weight: bold;
81
+ font-size: 22px; /* Tamaño más grande */
82
+ text-transform: uppercase; /* Texto en mayúsculas */
83
+ border: 1px solid #000000; /* Borde negro de 1px */
84
+ border-radius: 8px;
85
+ display: block;
86
+ margin: 0 auto; /* Centramos el botón */
87
+ }
88
+ div.stButton > button:hover {
89
+ background-color: #FFD700; /* Color al pasar el mouse */
90
+ color: black; /* Texto sigue en negro */
91
+ }
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:", ["Inglés", "Español"])
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.")