Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +2,10 @@ import gradio as gr
|
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import requests
|
| 5 |
-
from mega import Mega
|
| 6 |
from datetime import datetime
|
| 7 |
import tempfile
|
|
|
|
|
|
|
| 8 |
|
| 9 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 10 |
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
|
@@ -17,79 +18,94 @@ TOP_P = 0.95
|
|
| 17 |
# Credenciales de MEGA
|
| 18 |
MEGA_EMAIL = os.environ.get("MEGA_EMAIL")
|
| 19 |
MEGA_PASSWORD = os.environ.get("MEGA_PASSWORD")
|
| 20 |
-
REMOTE_DESTINATION_FOLDER = "Conversations"
|
| 21 |
|
| 22 |
-
def
|
| 23 |
-
"""
|
| 24 |
try:
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
m = mega.login(MEGA_EMAIL, MEGA_PASSWORD)
|
| 34 |
-
print("Conexi贸n exitosa
|
| 35 |
-
return m
|
| 36 |
-
|
| 37 |
except Exception as e:
|
| 38 |
-
print(f"
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
try:
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
"""
|
| 54 |
try:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
#
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
return folder[0] # Retorna el ID de la carpeta creada
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
-
print(f"Error
|
| 69 |
-
return
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
"""
|
| 73 |
if not MEGA_EMAIL or not MEGA_PASSWORD:
|
| 74 |
print("Warning: Credenciales de MEGA no configuradas.")
|
|
|
|
| 75 |
return
|
| 76 |
|
| 77 |
try:
|
| 78 |
-
# Conectarse a MEGA
|
| 79 |
-
mega_client = get_mega_client()
|
| 80 |
-
if not mega_client:
|
| 81 |
-
print("No se pudo establecer conexi贸n con MEGA. Guardando localmente como respaldo.")
|
| 82 |
-
# Guardar localmente como respaldo
|
| 83 |
-
save_locally_as_backup(session_data)
|
| 84 |
-
return
|
| 85 |
-
|
| 86 |
-
# Asegurar que existe la carpeta de conversaciones
|
| 87 |
-
conversations_folder_id = ensure_conversations_folder(mega_client)
|
| 88 |
-
if not conversations_folder_id:
|
| 89 |
-
print("No se pudo crear/acceder a la carpeta de conversaciones")
|
| 90 |
-
save_locally_as_backup(session_data)
|
| 91 |
-
return
|
| 92 |
-
|
| 93 |
# Formatear el log de la conversaci贸n
|
| 94 |
formatted_log = ""
|
| 95 |
for user_msg, assistant_msg in session_data:
|
|
@@ -108,24 +124,57 @@ def persist_data(session_data):
|
|
| 108 |
temp_file_path = temp_file.name
|
| 109 |
|
| 110 |
try:
|
| 111 |
-
#
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
# Renombrar el archivo subido
|
| 115 |
-
mega_client.rename(uploaded_file, log_name)
|
| 116 |
-
|
| 117 |
-
print(f"Log guardado exitosamente en MEGA: {log_name}")
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
finally:
|
| 120 |
# Limpiar archivo temporal
|
| 121 |
-
os.
|
|
|
|
| 122 |
|
| 123 |
except Exception as e:
|
| 124 |
-
print(f"Error durante la persistencia de datos
|
| 125 |
save_locally_as_backup(session_data)
|
| 126 |
|
| 127 |
def save_locally_as_backup(session_data):
|
| 128 |
-
"""Guarda las conversaciones localmente como respaldo
|
| 129 |
try:
|
| 130 |
# Formatear el log de la conversaci贸n
|
| 131 |
formatted_log = ""
|
|
@@ -210,7 +259,7 @@ def respond(message, history: list[tuple[str, str]]):
|
|
| 210 |
yield "Lo siento, ocurri贸 un error al procesar tu solicitud."
|
| 211 |
else:
|
| 212 |
current_session = history + [(message, accumulated_response)]
|
| 213 |
-
|
| 214 |
|
| 215 |
demo = gr.ChatInterface(
|
| 216 |
respond,
|
|
|
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import requests
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
import tempfile
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
|
| 10 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 11 |
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
|
|
|
| 18 |
# Credenciales de MEGA
|
| 19 |
MEGA_EMAIL = os.environ.get("MEGA_EMAIL")
|
| 20 |
MEGA_PASSWORD = os.environ.get("MEGA_PASSWORD")
|
| 21 |
+
REMOTE_DESTINATION_FOLDER = "Conversations"
|
| 22 |
|
| 23 |
+
def install_megapy():
|
| 24 |
+
"""Instala megapy si no est谩 disponible"""
|
| 25 |
try:
|
| 26 |
+
import megapy
|
| 27 |
+
return True
|
| 28 |
+
except ImportError:
|
| 29 |
+
try:
|
| 30 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "megapy"])
|
| 31 |
+
import megapy
|
| 32 |
+
return True
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"No se pudo instalar megapy: {e}")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
def get_mega_client_simple():
|
| 38 |
+
"""Intenta conectar usando diferentes m茅todos"""
|
| 39 |
+
|
| 40 |
+
# M茅todo 1: Intentar mega.py
|
| 41 |
+
try:
|
| 42 |
+
from mega import Mega
|
| 43 |
+
print("Usando mega.py...")
|
| 44 |
+
mega = Mega({'verbose': False})
|
| 45 |
m = mega.login(MEGA_EMAIL, MEGA_PASSWORD)
|
| 46 |
+
print("Conexi贸n exitosa con mega.py")
|
| 47 |
+
return m, "mega.py"
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
+
print(f"mega.py fall贸: {e}")
|
| 50 |
+
|
| 51 |
+
# M茅todo 2: Intentar megapy
|
| 52 |
+
if install_megapy():
|
| 53 |
try:
|
| 54 |
+
import megapy
|
| 55 |
+
print("Usando megapy...")
|
| 56 |
+
client = megapy.MegaApi()
|
| 57 |
+
# Aqu铆 implementar铆as la l贸gica de megapy
|
| 58 |
+
print("megapy inicializado (requiere implementaci贸n adicional)")
|
| 59 |
+
return None, "megapy"
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"megapy fall贸: {e}")
|
| 62 |
+
|
| 63 |
+
# M茅todo 3: Usar megatools (si est谩 disponible)
|
| 64 |
+
try:
|
| 65 |
+
result = subprocess.run(['which', 'megaput'], capture_output=True, text=True)
|
| 66 |
+
if result.returncode == 0:
|
| 67 |
+
print("Encontrado megatools, usando m茅todo de l铆nea de comandos")
|
| 68 |
+
return "megatools", "megatools"
|
| 69 |
+
except Exception as e:
|
| 70 |
+
print(f"megatools no disponible: {e}")
|
| 71 |
+
|
| 72 |
+
return None, None
|
| 73 |
|
| 74 |
+
def upload_with_megatools(file_path, remote_path):
|
| 75 |
+
"""Sube archivo usando megatools"""
|
| 76 |
try:
|
| 77 |
+
# Configurar credenciales
|
| 78 |
+
config_content = f"""[Login]
|
| 79 |
+
Username = {MEGA_EMAIL}
|
| 80 |
+
Password = {MEGA_PASSWORD}
|
| 81 |
+
"""
|
| 82 |
+
config_path = "/tmp/.megarc"
|
| 83 |
+
with open(config_path, 'w') as f:
|
| 84 |
+
f.write(config_content)
|
| 85 |
|
| 86 |
+
# Subir archivo
|
| 87 |
+
cmd = ['megaput', '--config', config_path, '--path', f'/{REMOTE_DESTINATION_FOLDER}', file_path]
|
| 88 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
|
|
| 89 |
|
| 90 |
+
if result.returncode == 0:
|
| 91 |
+
print("Archivo subido exitosamente con megatools")
|
| 92 |
+
return True
|
| 93 |
+
else:
|
| 94 |
+
print(f"Error con megatools: {result.stderr}")
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
except Exception as e:
|
| 98 |
+
print(f"Error usando megatools: {e}")
|
| 99 |
+
return False
|
| 100 |
|
| 101 |
+
def persist_data_simple(session_data):
|
| 102 |
+
"""Versi贸n simplificada para guardar datos"""
|
| 103 |
if not MEGA_EMAIL or not MEGA_PASSWORD:
|
| 104 |
print("Warning: Credenciales de MEGA no configuradas.")
|
| 105 |
+
save_locally_as_backup(session_data)
|
| 106 |
return
|
| 107 |
|
| 108 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
# Formatear el log de la conversaci贸n
|
| 110 |
formatted_log = ""
|
| 111 |
for user_msg, assistant_msg in session_data:
|
|
|
|
| 124 |
temp_file_path = temp_file.name
|
| 125 |
|
| 126 |
try:
|
| 127 |
+
# Intentar diferentes m茅todos de subida
|
| 128 |
+
mega_client, method = get_mega_client_simple()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
if method == "mega.py" and mega_client:
|
| 131 |
+
# M茅todo original con mega.py
|
| 132 |
+
try:
|
| 133 |
+
files = mega_client.get_files()
|
| 134 |
+
conversations_folder_id = None
|
| 135 |
+
|
| 136 |
+
# Buscar carpeta Conversations
|
| 137 |
+
for file_id, file_info in files.items():
|
| 138 |
+
if file_info['a'] and file_info['a'].get('n') == REMOTE_DESTINATION_FOLDER:
|
| 139 |
+
conversations_folder_id = file_id
|
| 140 |
+
break
|
| 141 |
+
|
| 142 |
+
# Crear carpeta si no existe
|
| 143 |
+
if not conversations_folder_id:
|
| 144 |
+
folder = mega_client.create_folder(REMOTE_DESTINATION_FOLDER)
|
| 145 |
+
conversations_folder_id = folder[0]
|
| 146 |
+
|
| 147 |
+
# Subir archivo
|
| 148 |
+
uploaded_file = mega_client.upload(temp_file_path, conversations_folder_id)
|
| 149 |
+
mega_client.rename(uploaded_file, log_name)
|
| 150 |
+
print(f"Log guardado exitosamente en MEGA con mega.py: {log_name}")
|
| 151 |
+
|
| 152 |
+
except Exception as e:
|
| 153 |
+
print(f"Error con mega.py: {e}")
|
| 154 |
+
save_locally_as_backup(session_data)
|
| 155 |
+
|
| 156 |
+
elif method == "megatools":
|
| 157 |
+
# Usar megatools
|
| 158 |
+
if upload_with_megatools(temp_file_path, log_name):
|
| 159 |
+
print(f"Log guardado con megatools: {log_name}")
|
| 160 |
+
else:
|
| 161 |
+
save_locally_as_backup(session_data)
|
| 162 |
+
else:
|
| 163 |
+
# Fallback a guardado local
|
| 164 |
+
print("No se pudo conectar a MEGA, guardando localmente")
|
| 165 |
+
save_locally_as_backup(session_data)
|
| 166 |
+
|
| 167 |
finally:
|
| 168 |
# Limpiar archivo temporal
|
| 169 |
+
if os.path.exists(temp_file_path):
|
| 170 |
+
os.unlink(temp_file_path)
|
| 171 |
|
| 172 |
except Exception as e:
|
| 173 |
+
print(f"Error durante la persistencia de datos: {e}")
|
| 174 |
save_locally_as_backup(session_data)
|
| 175 |
|
| 176 |
def save_locally_as_backup(session_data):
|
| 177 |
+
"""Guarda las conversaciones localmente como respaldo"""
|
| 178 |
try:
|
| 179 |
# Formatear el log de la conversaci贸n
|
| 180 |
formatted_log = ""
|
|
|
|
| 259 |
yield "Lo siento, ocurri贸 un error al procesar tu solicitud."
|
| 260 |
else:
|
| 261 |
current_session = history + [(message, accumulated_response)]
|
| 262 |
+
persist_data_simple(current_session)
|
| 263 |
|
| 264 |
demo = gr.ChatInterface(
|
| 265 |
respond,
|