Spaces:
Running
Running
File size: 5,595 Bytes
f5f3ef7 1262652 341e8c3 f5f3ef7 341e8c3 f5f3ef7 1262652 341e8c3 f5f3ef7 1262652 341e8c3 f5f3ef7 1262652 f5f3ef7 341e8c3 f5f3ef7 f8cfa08 f5f3ef7 1e502ed 8b57bc2 f5f3ef7 24967bd 412a4bc 075a4ec 5d4abba a190d7d 5d4abba 389b675 24967bd 075a4ec 24967bd 075a4ec 24967bd f8cfa08 f5f3ef7 412a4bc f8cfa08 6a766bd 53d5893 25a44d4 53d5893 412a4bc 53d5893 1262652 075a4ec 758652e 1f182e0 412a4bc 25a44d4 f8cfa08 53d5893 f5f3ef7 412a4bc 24967bd f8cfa08 53d5893 f8cfa08 53d5893 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
from PIL import Image
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Function to get response from Gemini model
def get_gemini_response(input_prompt, image_data, genre, length, language, mood):
model = genai.GenerativeModel('gemini-1.5-flash')
# If both image and text are provided
if image_data and input_prompt:
full_prompt = f"""
You are a famous creative writer. Look at the image provided and also consider the following prompt: "{input_prompt}".
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.
"""
response = model.generate_content([full_prompt, image_data[0]])
# If only image is provided
elif image_data:
full_prompt = f"""
You are a famous creative writer. Look at the image provided and create a {length} {genre} in {language}.
The {genre} should be {mood}. The {genre} should be based on the image and contain realistic and emotional elements.
"""
response = model.generate_content([full_prompt, image_data[0]])
# If only text is provided
elif input_prompt:
full_prompt = f"""
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:
"{input_prompt}"
Make sure it contains realistic and emotional elements.
"""
response = model.generate_content([full_prompt])
# If neither image nor text is provided
else:
raise ValueError("Please provide either an image or a text prompt.")
# Check if response is valid and return text
if response and response.parts:
return response.parts[0].text
else:
raise ValueError("Sorry, please try a different combination of inputs.")
# Function to setup uploaded image
def input_image_setup(uploaded_file):
if uploaded_file is not None:
bytes_data = uploaded_file.getvalue()
image_parts = [
{
"mime_type": uploaded_file.type,
"data": bytes_data
}
]
return image_parts
else:
return None
# Initialize Streamlit app
st.set_page_config(page_title="Poetic Vision", page_icon=":pencil:", layout="wide") # Set layout to wide
# Main UI components
st.markdown("<h1 style='text-align: center;'>VisionTales</h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center;'>Convierte tus ideas en historias inolvidables.</h3>", unsafe_allow_html=True)
# Add custom CSS for the button
st.markdown("""
<style>
div.stButton > button {
background-color: #FFCC00; /* Color llamativo */
color: black; /* Texto en negro */
width: 90%;
height: 60px;
font-weight: bold;
font-size: 22px; /* Tamaño más grande */
text-transform: uppercase; /* Texto en mayúsculas */
border: 1px solid #000000; /* Borde negro de 1px */
border-radius: 8px;
display: block;
margin: 0 auto; /* Centramos el botón */
}
div.stButton > button:hover {
background-color: #FFD700; /* Color al pasar el mouse */
color: black; /* Texto sigue en negro */
}
</style>
""", unsafe_allow_html=True)
# Create two columns for layout (40% and 60%)
col1, col2 = st.columns([2, 3]) # 2 + 3 = 5 parts total
# Variables para valores predeterminados
default_language = "Español"
with col1:
# Subir imagen primero
uploaded_file = st.file_uploader("Elegir una imagen...", type=["jpg", "jpeg", "png"])
# Agrupar opciones en un desplegable con un nuevo título
with st.expander("Clic para personalizar tu historia", expanded=False): # El desplegable está cerrado por defecto
input_prompt = st.text_input("Escribe de qué quieres que trate tu historia (opcional):", placeholder="Escribe tu mensaje aquí...")
genre = st.selectbox("Tipo de texto:", ["Historia", "Shayari", "Sher", "Poema", "Cita"])
length = st.selectbox("Longitud del texto:", ["Corto", "Largo"])
language = st.selectbox("Idioma del texto:", ["Inglés", "Español"], index=1) # Español por defecto
mood = st.selectbox("Estado de ánimo:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
# Generate button con el nuevo estilo, centrado y ajustado
submit = st.button("Escribir mi historia")
# Reset button
if st.button("Reiniciar valores"):
uploaded_file = None
input_prompt = ""
genre = "Historia"
length = "Corto"
language = "Español" # Reiniciar a Español
mood = "Emocional"
st.experimental_rerun() # Reiniciar la app
# Display uploaded image
if uploaded_file is not None:
image = Image.open(uploaded_file)
col1.image(image, caption="Imagen subida", use_column_width=True)
# Handle submit action
if submit:
if uploaded_file or input_prompt:
try:
image_data = input_image_setup(uploaded_file)
response = get_gemini_response(input_prompt, image_data, genre, length, language, mood)
col2.subheader("Contenido generado:")
col2.write(response)
except ValueError as e:
col2.error(f"Error: {str(e)}")
else:
col2.error("Por favor, sube una imagen o proporciona un mensaje.")
|