gnosticdev commited on
Commit
b8e1c73
verified
1 Parent(s): 2251b3a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -76
app.py CHANGED
@@ -1,54 +1,28 @@
 
1
  import streamlit as st
2
  import json
3
- import requests
4
  from streamlit_option_menu import option_menu
5
  from gemini_utility import (load_gemini_pro, gemini_pro_vision_responce)
6
  from PIL import Image
7
 
8
- # Funci贸n para traducir el rol a un formato que Streamlit entienda
9
- def translate_role_to_streamlit(role):
10
- if role == "user":
11
- return "user"
12
- elif role == "assistant":
13
- return "assistant"
14
- else:
15
- return "default" # Manejar otros roles si es necesario
16
-
17
- # Configuraci贸n de la p谩gina
18
  st.set_page_config(
19
  page_title="GnosticDev AI",
20
  page_icon="馃",
21
- layout="wide",
22
  initial_sidebar_state="expanded",
23
  )
24
 
25
- # Men煤 de opciones en el lateral izquierdo
26
- selected = option_menu(
27
- menu_title="Men煤",
28
- options=["System Prompt", "Chatbot", "Image Captioning"],
29
- icons=["gear", "chat", "camera"],
30
- default_index=0,
31
- orientation="vertical"
32
- )
33
-
34
- # Inicializar el estado de la sesi贸n
35
- if 'cookie_chat_history' not in st.session_state:
36
- st.session_state.cookie_chat_history = json.dumps([])
37
-
38
- if 'cookie_urls' not in st.session_state:
39
- st.session_state.cookie_urls = []
40
-
41
- if 'system_prompt' not in st.session_state:
42
- st.session_state.system_prompt = ""
43
-
44
  # Funci贸n para guardar el historial en cookies
45
  def save_chat_history(history):
 
46
  serializable_history = []
47
  for message in history:
48
  serializable_history.append({
49
  "role": message.role,
50
  "text": message.parts[0].text
51
  })
 
52
  st.session_state.cookie_chat_history = json.dumps(serializable_history)
53
 
54
  # Funci贸n para cargar el historial desde cookies
@@ -58,6 +32,7 @@ def load_chat_history():
58
  history = json.loads(st.session_state.cookie_chat_history)
59
  model = load_gemini_pro()
60
  chat = model.start_chat(history=[])
 
61
  if st.session_state.system_prompt:
62
  chat.send_message(st.session_state.system_prompt)
63
  for message in history:
@@ -75,15 +50,32 @@ def download_chat_history(history):
75
  chat_text += f"{message.role}: {message.parts[0].text}\n"
76
  return chat_text
77
 
78
- # Funci贸n para obtener contenido de URLs
79
- def fetch_url_content(url):
80
- try:
81
- response = requests.get(url)
82
- response.raise_for_status()
83
- return response.text
84
- except requests.RequestException as e:
85
- st.error(f"Error al acceder a {url}: {e}")
86
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  if selected == "System Prompt":
89
  st.title("Configuraci贸n del System Prompt")
@@ -95,38 +87,28 @@ if selected == "System Prompt":
95
  help="Escribe aqu铆 las instrucciones que definir谩n el comportamiento del AI"
96
  )
97
 
98
- urls_input = st.text_area(
99
- "Ingresa URLs de informaci贸n y documentos (separadas por comas)",
100
- value=", ".join(st.session_state.cookie_urls),
101
- height=100,
102
- help="Escribe aqu铆 las URLs que el AI puede usar como referencia, separadas por comas."
103
- )
104
-
105
- if st.button("Guardar System Prompt y URLs"):
106
  st.session_state.system_prompt = new_system_prompt
107
- st.session_state.cookie_urls = [url.strip() for url in urls_input.split(",") if url.strip()]
108
  if "chat_session" in st.session_state:
109
  del st.session_state.chat_session
110
- st.success("System Prompt y URLs actualizados con 茅xito!")
111
 
112
  if st.session_state.system_prompt:
113
  st.markdown("### System Prompt Actual:")
114
  st.info(st.session_state.system_prompt)
115
-
116
- if st.session_state.cookie_urls:
117
- st.markdown("### URLs Guardadas:")
118
- st.info(", ".join(st.session_state.cookie_urls))
119
 
120
  elif selected == "Chatbot":
121
  model = load_gemini_pro()
122
 
 
123
  if "chat_session" not in st.session_state:
124
  loaded_chat = load_chat_history()
125
- if loaded_chat:
126
  st.session_state.chat_session = loaded_chat
127
- else:
128
- st.session_state.chat_session = model.start_chat(history=[])
129
- if st.session_state.system_prompt:
130
  st.session_state.chat_session.send_message(st.session_state.system_prompt)
131
 
132
  st.title("Gnosticdev Chatbot")
@@ -140,27 +122,10 @@ elif selected == "Chatbot":
140
  with st.chat_message(translate_role_to_streamlit(message.role)):
141
  st.markdown(message.parts[0].text)
142
 
143
- # Campo de entrada
144
  user_prompt = st.chat_input("Preguntame algo...")
145
  if user_prompt:
146
  st.chat_message("user").markdown(user_prompt)
147
-
148
- # Obtener las URLs guardadas
149
- urls = st.session_state.get('cookie_urls', [])
150
- fetched_contents = []
151
-
152
- if urls:
153
- # L贸gica para consultar las URLs y obtener informaci贸n
154
- for url in urls:
155
- content = fetch_url_content(url)
156
- if content:
157
- fetched_contents.append(content)
158
-
159
- # Aqu铆 puedes procesar el contenido obtenido de las URLs
160
- combined_content = "\n\n".join(fetched_contents)
161
- user_prompt += f"\n\nInformaci贸n adicional de URLs:\n{combined_content}"
162
-
163
- # Enviar el mensaje del usuario al modelo
164
  gemini_response = st.session_state.chat_session.send_message(user_prompt)
165
  with st.chat_message("assistant"):
166
  st.markdown(gemini_response.text)
 
1
+ import os
2
  import streamlit as st
3
  import json
 
4
  from streamlit_option_menu import option_menu
5
  from gemini_utility import (load_gemini_pro, gemini_pro_vision_responce)
6
  from PIL import Image
7
 
8
+ # Setting the page config
 
 
 
 
 
 
 
 
 
9
  st.set_page_config(
10
  page_title="GnosticDev AI",
11
  page_icon="馃",
12
+ layout="centered",
13
  initial_sidebar_state="expanded",
14
  )
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  # Funci贸n para guardar el historial en cookies
17
  def save_chat_history(history):
18
+ # Convertir el historial a un formato serializable
19
  serializable_history = []
20
  for message in history:
21
  serializable_history.append({
22
  "role": message.role,
23
  "text": message.parts[0].text
24
  })
25
+ # Guardar en cookie
26
  st.session_state.cookie_chat_history = json.dumps(serializable_history)
27
 
28
  # Funci贸n para cargar el historial desde cookies
 
32
  history = json.loads(st.session_state.cookie_chat_history)
33
  model = load_gemini_pro()
34
  chat = model.start_chat(history=[])
35
+ # Reconstruir el historial
36
  if st.session_state.system_prompt:
37
  chat.send_message(st.session_state.system_prompt)
38
  for message in history:
 
50
  chat_text += f"{message.role}: {message.parts[0].text}\n"
51
  return chat_text
52
 
53
+ # Inicializar estados
54
+ if "system_prompt" not in st.session_state:
55
+ st.session_state.system_prompt = st.session_state.get('cookie_system_prompt', "")
56
+
57
+ with st.sidebar:
58
+ selected = option_menu(
59
+ "GD AI",
60
+ ["System Prompt", "Chatbot", "Image Captioning"],
61
+ menu_icon="robot",
62
+ icons=['gear', 'chat-dots-fill', 'image-fill'],
63
+ default_index=0
64
+ )
65
+
66
+ # Bot贸n para borrar historial
67
+ if st.button("Borrar Historial"):
68
+ if 'cookie_chat_history' in st.session_state:
69
+ del st.session_state.cookie_chat_history
70
+ if 'chat_session' in st.session_state:
71
+ del st.session_state.chat_session
72
+ st.success("Historial borrado!")
73
+
74
+ def translate_role_to_streamlit(user_role):
75
+ if user_role == "model":
76
+ return "assistant"
77
+ else:
78
+ return user_role
79
 
80
  if selected == "System Prompt":
81
  st.title("Configuraci贸n del System Prompt")
 
87
  help="Escribe aqu铆 las instrucciones que definir谩n el comportamiento del AI"
88
  )
89
 
90
+ if st.button("Guardar System Prompt"):
 
 
 
 
 
 
 
91
  st.session_state.system_prompt = new_system_prompt
92
+ st.session_state.cookie_system_prompt = new_system_prompt # Guardar en cookie
93
  if "chat_session" in st.session_state:
94
  del st.session_state.chat_session
95
+ st.success("System Prompt actualizado con 茅xito!")
96
 
97
  if st.session_state.system_prompt:
98
  st.markdown("### System Prompt Actual:")
99
  st.info(st.session_state.system_prompt)
 
 
 
 
100
 
101
  elif selected == "Chatbot":
102
  model = load_gemini_pro()
103
 
104
+ # Inicializar o cargar sesi贸n de chat
105
  if "chat_session" not in st.session_state:
106
  loaded_chat = load_chat_history()
107
+ if loaded_chat:
108
  st.session_state.chat_session = loaded_chat
109
+ else:
110
+ st.session_state.chat_session = model.start_chat(history=[])
111
+ if st.session_state.system_prompt:
112
  st.session_state.chat_session.send_message(st.session_state.system_prompt)
113
 
114
  st.title("Gnosticdev Chatbot")
 
122
  with st.chat_message(translate_role_to_streamlit(message.role)):
123
  st.markdown(message.parts[0].text)
124
 
125
+ # Campo de entrada
126
  user_prompt = st.chat_input("Preguntame algo...")
127
  if user_prompt:
128
  st.chat_message("user").markdown(user_prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  gemini_response = st.session_state.chat_session.send_message(user_prompt)
130
  with st.chat_message("assistant"):
131
  st.markdown(gemini_response.text)