File size: 6,928 Bytes
4227970 59bfaac fa92574 ea092fd fa92574 509b02d fa92574 4b02bb7 fa92574 4227970 fa92574 509b02d fa92574 4b02bb7 fa92574 4b02bb7 fa92574 4b02bb7 fa92574 4227970 4b02bb7 4227970 4b02bb7 4227970 2b28b66 ea092fd 4227970 4b02bb7 4227970 2b28b66 4b02bb7 ea092fd 509b02d ea092fd 509b02d ea092fd 4b02bb7 ea092fd 4b02bb7 ea092fd 4b02bb7 ea092fd 4b02bb7 ea092fd 509b02d 4b02bb7 ea092fd 5115a7b 4b02bb7 f54757c 2251b3a f54757c b8e1c73 f54757c b8e1c73 3e2f4cc b8e1c73 a36d2f3 f54757c 3e2f4cc f54757c a36d2f3 3e2f4cc 509b02d f54757c ea092fd f54757c a36d2f3 3e2f4cc f54757c 509b02d |
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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
import os
import streamlit as st
import json
import requests
import re
from bs4 import BeautifulSoup
from streamlit_option_menu import option_menu
from gemini_utility import (load_gemini_pro, gemini_pro_vision_responce)
from PIL import Image
# Setting the page config
st.set_page_config(
page_title="GnosticDev AI",
page_icon="馃",
layout="centered",
initial_sidebar_state="expanded",
)
CONFIG_FILE = "config.json"
# Funci贸n para cargar configuraciones desde un archivo JSON
def load_config():
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r") as file:
return json.load(file)
except Exception as e:
st.error(f"Error cargando configuraciones: {e}")
return {}
# Funci贸n para guardar configuraciones en un archivo JSON
def save_config(config):
try:
with open(CONFIG_FILE, "w") as file:
json.dump(config, file, indent=4)
except Exception as e:
st.error(f"Error guardando configuraciones: {e}")
# Cargar configuraciones al inicio
config = load_config()
if "system_prompt" not in config:
config["system_prompt"] = ""
# Inicializar estados
if "system_prompt" not in st.session_state:
st.session_state.system_prompt = config["system_prompt"]
def save_chat_history(history):
serializable_history = []
for message in history:
serializable_history.append({
"role": message.role,
"text": message.parts[0].text
})
st.session_state.cookie_chat_history = json.dumps(serializable_history)
def load_chat_history():
if 'cookie_chat_history' in st.session_state:
try:
history = json.loads(st.session_state.cookie_chat_history)
model = load_gemini_pro()
chat = model.start_chat(history=[])
if st.session_state.system_prompt:
chat.send_message(st.session_state.system_prompt)
for message in history:
if message["role"] != "model" or not message["text"].startswith(st.session_state.system_prompt):
chat.send_message(message["text"])
return chat
except Exception as e:
st.error(f"Error cargando el historial: {e}")
return None
with st.sidebar:
selected = option_menu(
"GD AI",
["System Prompt", "Chatbot", "Image Captioning"],
menu_icon="robot",
icons=['gear', 'chat-dots-fill', 'image-fill'],
default_index=0
)
if st.button("Borrar Historial"):
if 'cookie_chat_history' in st.session_state:
del st.session_state.cookie_chat_history
if 'chat_session' in st.session_state:
del st.session_state.chat_session
st.success("Historial borrado!")
def translate_role_to_streamlit(user_role):
if user_role == "model":
return "assistant"
else:
return user_role
def extract_urls(text):
url_pattern = r"(https?://\S+)"
urls = re.findall(url_pattern, text)
return urls
def fetch_url_content(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
return f"Error al acceder a la URL '{url}': {e}"
def process_url_content(content):
try:
soup = BeautifulSoup(content, "html.parser")
text = soup.get_text(" ", strip=True)
return text
except Exception as e:
return f"Error al procesar el contenido HTML: {e}"
def process_urls_in_prompt(prompt):
urls = extract_urls(prompt)
new_prompt = prompt
for url in urls:
content = fetch_url_content(url)
if content.startswith("Error"):
new_prompt = new_prompt.replace(url, content)
else:
processed_content = process_url_content(content)
new_prompt = new_prompt.replace(url, processed_content)
return new_prompt
if selected == "System Prompt":
st.title("Configuraci贸n del System Prompt")
new_system_prompt = st.text_area(
"Ingresa las instrucciones para el AI (System Prompt), incluyendo URLs",
value=st.session_state.system_prompt,
height=300,
help="Escribe aqu铆 las instrucciones que definir谩n el comportamiento del AI. Puedes incluir URLs."
)
if st.button("Guardar System Prompt"):
processed_prompt = process_urls_in_prompt(new_system_prompt)
st.session_state.system_prompt = processed_prompt
config["system_prompt"] = processed_prompt
save_config(config)
if "chat_session" in st.session_state:
del st.session_state.chat_session
st.success("System Prompt actualizado con 茅xito!")
elif selected == "Chatbot":
model = load_gemini_pro()
if "chat_session" not in st.session_state:
loaded_chat = load_chat_history()
if loaded_chat:
st.session_state.chat_session = loaded_chat
else:
# Crea una nueva sesi贸n de chat sin enviar el system_prompt como mensaje inicial
st.session_state.chat_session = model.start_chat(history=[])
st.title("Gnosticdev Chatbot")
# Muestra solo el historial del chat, si existe
for message in st.session_state.chat_session.history:
with st.chat_message(translate_role_to_streamlit(message.role)):
st.markdown(message.parts[0].text)
# Entrada del usuario
user_prompt = st.chat_input("Preg煤ntame algo...")
if user_prompt:
processed_user_prompt = process_urls_in_prompt(user_prompt)
st.chat_message("user").markdown(processed_user_prompt)
gemini_response = st.session_state.chat_session.send_message(processed_user_prompt)
with st.chat_message("assistant"):
st.markdown(gemini_response.text)
save_chat_history(st.session_state.chat_session.history)
elif selected == "Image Captioning":
st.title("Image Caption Generation馃摳")
upload_image = st.file_uploader("Sube una imagen...", type=["jpg", "jpeg", "png"])
if upload_image and st.button("Generar"):
try:
# Cargar y mostrar la imagen
image = Image.open(upload_image)
col1, col2 = st.columns(2)
with col1:
st.image(image, caption="Imagen subida", use_column_width=True)
# Generar un subt铆tulo usando una funci贸n de visi贸n AI
default_prompt = "Escribe un subt铆tulo para esta imagen"
caption = gemini_pro_vision_responce(default_prompt, image)
# Mostrar el resultado
with col2:
st.info(caption)
except Exception as e:
st.error(f"Error procesando la imagen: {e}")
# Mensaje por defecto si ninguna secci贸n est谩 seleccionada
else:
st.write("Selecciona una opci贸n en el men煤 para comenzar.")
|