Update app.py
Browse files
app.py
CHANGED
@@ -5,7 +5,7 @@ import requests
|
|
5 |
import re
|
6 |
from bs4 import BeautifulSoup
|
7 |
from streamlit_option_menu import option_menu
|
8 |
-
from gemini_utility import (load_gemini_pro, gemini_pro_vision_responce)
|
9 |
from PIL import Image
|
10 |
|
11 |
# Setting the page config
|
@@ -16,7 +16,35 @@ st.set_page_config(
|
|
16 |
initial_sidebar_state="expanded",
|
17 |
)
|
18 |
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
def save_chat_history(history):
|
21 |
serializable_history = []
|
22 |
for message in history:
|
@@ -26,7 +54,6 @@ def save_chat_history(history):
|
|
26 |
})
|
27 |
st.session_state.cookie_chat_history = json.dumps(serializable_history)
|
28 |
|
29 |
-
# Funci贸n para cargar el historial desde cookies (sin cambios)
|
30 |
def load_chat_history():
|
31 |
if 'cookie_chat_history' in st.session_state:
|
32 |
try:
|
@@ -43,10 +70,6 @@ def load_chat_history():
|
|
43 |
st.error(f"Error cargando el historial: {e}")
|
44 |
return None
|
45 |
|
46 |
-
# Inicializar estados (sin cambios)
|
47 |
-
if "system_prompt" not in st.session_state:
|
48 |
-
st.session_state.system_prompt = st.session_state.get('cookie_system_prompt', "")
|
49 |
-
|
50 |
with st.sidebar:
|
51 |
selected = option_menu(
|
52 |
"GD AI",
|
@@ -69,7 +92,6 @@ def translate_role_to_streamlit(user_role):
|
|
69 |
else:
|
70 |
return user_role
|
71 |
|
72 |
-
|
73 |
def extract_urls(text):
|
74 |
url_pattern = r"(https?://\S+)"
|
75 |
urls = re.findall(url_pattern, text)
|
@@ -77,7 +99,7 @@ def extract_urls(text):
|
|
77 |
|
78 |
def fetch_url_content(url):
|
79 |
try:
|
80 |
-
response = requests.get(url, timeout=10)
|
81 |
response.raise_for_status()
|
82 |
return response.text
|
83 |
except requests.exceptions.RequestException as e:
|
@@ -86,19 +108,17 @@ def fetch_url_content(url):
|
|
86 |
def process_url_content(content):
|
87 |
try:
|
88 |
soup = BeautifulSoup(content, "html.parser")
|
89 |
-
# Extrae solo el texto del cuerpo principal, ignorando etiquetas de scripts y estilos
|
90 |
text = soup.get_text(" ", strip=True)
|
91 |
return text
|
92 |
except Exception as e:
|
93 |
return f"Error al procesar el contenido HTML: {e}"
|
94 |
|
95 |
-
|
96 |
def process_urls_in_prompt(prompt):
|
97 |
urls = extract_urls(prompt)
|
98 |
new_prompt = prompt
|
99 |
for url in urls:
|
100 |
content = fetch_url_content(url)
|
101 |
-
if content.startswith("Error"):
|
102 |
new_prompt = new_prompt.replace(url, content)
|
103 |
else:
|
104 |
processed_content = process_url_content(content)
|
@@ -117,7 +137,8 @@ if selected == "System Prompt":
|
|
117 |
if st.button("Guardar System Prompt"):
|
118 |
processed_prompt = process_urls_in_prompt(new_system_prompt)
|
119 |
st.session_state.system_prompt = processed_prompt
|
120 |
-
|
|
|
121 |
if "chat_session" in st.session_state:
|
122 |
del st.session_state.chat_session
|
123 |
st.success("System Prompt actualizado con 茅xito!")
|
@@ -126,7 +147,6 @@ if selected == "System Prompt":
|
|
126 |
st.markdown("### System Prompt Actual:")
|
127 |
st.info(st.session_state.system_prompt)
|
128 |
|
129 |
-
|
130 |
elif selected == "Chatbot":
|
131 |
model = load_gemini_pro()
|
132 |
if "chat_session" not in st.session_state:
|
@@ -146,7 +166,7 @@ elif selected == "Chatbot":
|
|
146 |
with st.chat_message(translate_role_to_streamlit(message.role)):
|
147 |
st.markdown(message.parts[0].text)
|
148 |
|
149 |
-
user_prompt = st.chat_input("
|
150 |
if user_prompt:
|
151 |
processed_user_prompt = process_urls_in_prompt(user_prompt)
|
152 |
st.chat_message("user").markdown(processed_user_prompt)
|
@@ -155,16 +175,30 @@ elif selected == "Chatbot":
|
|
155 |
st.markdown(gemini_response.text)
|
156 |
save_chat_history(st.session_state.chat_session.history)
|
157 |
|
158 |
-
|
159 |
elif selected == "Image Captioning":
|
160 |
st.title("Image Caption Generation馃摳")
|
161 |
-
upload_image = st.file_uploader("
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import re
|
6 |
from bs4 import BeautifulSoup
|
7 |
from streamlit_option_menu import option_menu
|
8 |
+
from gemini_utility import (load_gemini_pro, gemini_pro_vision_responce)
|
9 |
from PIL import Image
|
10 |
|
11 |
# Setting the page config
|
|
|
16 |
initial_sidebar_state="expanded",
|
17 |
)
|
18 |
|
19 |
+
CONFIG_FILE = "config.json"
|
20 |
+
|
21 |
+
# Funci贸n para cargar configuraciones desde un archivo JSON
|
22 |
+
def load_config():
|
23 |
+
if os.path.exists(CONFIG_FILE):
|
24 |
+
try:
|
25 |
+
with open(CONFIG_FILE, "r") as file:
|
26 |
+
return json.load(file)
|
27 |
+
except Exception as e:
|
28 |
+
st.error(f"Error cargando configuraciones: {e}")
|
29 |
+
return {}
|
30 |
+
|
31 |
+
# Funci贸n para guardar configuraciones en un archivo JSON
|
32 |
+
def save_config(config):
|
33 |
+
try:
|
34 |
+
with open(CONFIG_FILE, "w") as file:
|
35 |
+
json.dump(config, file, indent=4)
|
36 |
+
except Exception as e:
|
37 |
+
st.error(f"Error guardando configuraciones: {e}")
|
38 |
+
|
39 |
+
# Cargar configuraciones al inicio
|
40 |
+
config = load_config()
|
41 |
+
if "system_prompt" not in config:
|
42 |
+
config["system_prompt"] = ""
|
43 |
+
|
44 |
+
# Inicializar estados
|
45 |
+
if "system_prompt" not in st.session_state:
|
46 |
+
st.session_state.system_prompt = config["system_prompt"]
|
47 |
+
|
48 |
def save_chat_history(history):
|
49 |
serializable_history = []
|
50 |
for message in history:
|
|
|
54 |
})
|
55 |
st.session_state.cookie_chat_history = json.dumps(serializable_history)
|
56 |
|
|
|
57 |
def load_chat_history():
|
58 |
if 'cookie_chat_history' in st.session_state:
|
59 |
try:
|
|
|
70 |
st.error(f"Error cargando el historial: {e}")
|
71 |
return None
|
72 |
|
|
|
|
|
|
|
|
|
73 |
with st.sidebar:
|
74 |
selected = option_menu(
|
75 |
"GD AI",
|
|
|
92 |
else:
|
93 |
return user_role
|
94 |
|
|
|
95 |
def extract_urls(text):
|
96 |
url_pattern = r"(https?://\S+)"
|
97 |
urls = re.findall(url_pattern, text)
|
|
|
99 |
|
100 |
def fetch_url_content(url):
|
101 |
try:
|
102 |
+
response = requests.get(url, timeout=10)
|
103 |
response.raise_for_status()
|
104 |
return response.text
|
105 |
except requests.exceptions.RequestException as e:
|
|
|
108 |
def process_url_content(content):
|
109 |
try:
|
110 |
soup = BeautifulSoup(content, "html.parser")
|
|
|
111 |
text = soup.get_text(" ", strip=True)
|
112 |
return text
|
113 |
except Exception as e:
|
114 |
return f"Error al procesar el contenido HTML: {e}"
|
115 |
|
|
|
116 |
def process_urls_in_prompt(prompt):
|
117 |
urls = extract_urls(prompt)
|
118 |
new_prompt = prompt
|
119 |
for url in urls:
|
120 |
content = fetch_url_content(url)
|
121 |
+
if content.startswith("Error"):
|
122 |
new_prompt = new_prompt.replace(url, content)
|
123 |
else:
|
124 |
processed_content = process_url_content(content)
|
|
|
137 |
if st.button("Guardar System Prompt"):
|
138 |
processed_prompt = process_urls_in_prompt(new_system_prompt)
|
139 |
st.session_state.system_prompt = processed_prompt
|
140 |
+
config["system_prompt"] = processed_prompt
|
141 |
+
save_config(config)
|
142 |
if "chat_session" in st.session_state:
|
143 |
del st.session_state.chat_session
|
144 |
st.success("System Prompt actualizado con 茅xito!")
|
|
|
147 |
st.markdown("### System Prompt Actual:")
|
148 |
st.info(st.session_state.system_prompt)
|
149 |
|
|
|
150 |
elif selected == "Chatbot":
|
151 |
model = load_gemini_pro()
|
152 |
if "chat_session" not in st.session_state:
|
|
|
166 |
with st.chat_message(translate_role_to_streamlit(message.role)):
|
167 |
st.markdown(message.parts[0].text)
|
168 |
|
169 |
+
user_prompt = st.chat_input("Preg煤ntame algo...")
|
170 |
if user_prompt:
|
171 |
processed_user_prompt = process_urls_in_prompt(user_prompt)
|
172 |
st.chat_message("user").markdown(processed_user_prompt)
|
|
|
175 |
st.markdown(gemini_response.text)
|
176 |
save_chat_history(st.session_state.chat_session.history)
|
177 |
|
|
|
178 |
elif selected == "Image Captioning":
|
179 |
st.title("Image Caption Generation馃摳")
|
180 |
+
upload_image = st.file_uploader("Sube una imagen...", type=["jpg", "jpeg", "png"])
|
181 |
+
|
182 |
+
if upload_image and st.button("Generar"):
|
183 |
+
try:
|
184 |
+
# Cargar y mostrar la imagen
|
185 |
+
image = Image.open(upload_image)
|
186 |
+
col1, col2 = st.columns(2)
|
187 |
+
with col1:
|
188 |
+
st.image(image, caption="Imagen subida", use_column_width=True)
|
189 |
+
|
190 |
+
# Generar un subt铆tulo usando una funci贸n de visi贸n AI
|
191 |
+
default_prompt = "Escribe un subt铆tulo para esta imagen"
|
192 |
+
caption = gemini_pro_vision_responce(default_prompt, image)
|
193 |
+
|
194 |
+
# Mostrar el resultado
|
195 |
+
with col2:
|
196 |
+
st.info(caption)
|
197 |
+
except Exception as e:
|
198 |
+
st.error(f"Error procesando la imagen: {e}")
|
199 |
+
|
200 |
+
# Mensaje por defecto si ninguna secci贸n est谩 seleccionada
|
201 |
+
else:
|
202 |
+
st.write("Selecciona una opci贸n en el men煤 para comenzar.")
|
203 |
+
|
204 |
+
|