Spaces:
Sleeping
Sleeping
File size: 11,227 Bytes
7791411 5399f78 b57b66c 7791411 7dda575 7791411 a8aa8a6 7791411 |
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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
import gradio as gr
import time
import random
import openai
import os
import re
# Configuración OpenAI
try:
api_key = os.getenv("OPENAI_API_KEY")
if api_key and api_key.startswith("sk-"):
client = openai.OpenAI(api_key=api_key)
AI_ENABLED = True
print("✅ OpenAI configurado correctamente")
else:
client = None
AI_ENABLED = False
print("⚠️ Usando análisis automático (sin OpenAI)")
except Exception as e:
client = None
AI_ENABLED = False
print(f"⚠️ Error OpenAI: {e}")
# CSS FIJO - FUNCIONA EN MODO CLARO Y OSCURO
CSS_FIJO = """
.gradio-container, body, .markdown, .prose, .gr-box, .gr-form, .gr-button,
.gr-textbox, .gr-html, .gr-markdown {
color: #000000 !important;
background: #ffffff !important;
}
h1, h2, h3, h4, h5, h6, p, span, div, label {
color: #000000 !important;
}
button {
color: #000000 !important;
border: 2px solid #007bff !important;
background: #f8f9fa !important;
}
button:hover {
background: #007bff !important;
color: #ffffff !important;
}
.gr-container, .panel, .block, .container {
background: #ffffff !important;
color: #000000 !important;
}
* {
color: #000000 !important;
}
"""
def simulate_speed_test():
"""Simula métricas de velocidad realistas"""
download = round(random.uniform(10, 100), 2)
upload = round(random.uniform(5, 50), 2)
ping = round(random.uniform(15, 80), 2)
jitter = round(random.uniform(1, 10), 2)
return download, upload, ping, jitter
def analyze_with_openai(download, upload, ping, jitter):
"""Análisis con OpenAI MEJORADO - respuestas más detalladas"""
if not AI_ENABLED:
# Fallback más detallado
if download > 80:
return "CALIDAD: Excelente 🌟\nANALISIS: Tu conexión es ideal para streaming 4K, gaming online y teletrabajo simultáneo\nRECOMENDACIONES: [1. 💡 Mantén tu configuración actual] [2. 🎮 Perfecta para gaming competitivo] [3. 📊 Ideal para home office]"
elif download > 50:
return "CALIDAD: Muy Buena ✅\nANALISIS: Conexión excelente para streaming HD, videollamadas y uso familiar\nRECOMENDACIONES: [1. 💡 Buen rendimiento general] [2. 📺 Ideal para múltiples dispositivos] [3. ⚡ Optimizada para trabajo remoto]"
elif download > 25:
return "CALIDAD: Buena 📶\nANALISIS: Velocidad adecuada para navegación, redes sociales y streaming básico\nRECOMENDACIONES: [1. 💡 Considera mejorar tu plan] [2. 📡 Optimiza posición del router] [3. 🔄 Cierra apps no usadas]"
else:
return "CALIDAD: Regular ⚠️\nANALISIS: Conexión limitada, puede tener problemas con video HD y múltiples usuarios\nRECOMENDACIONES: [1. 💡 Actualiza tu plan de internet] [2. 📞 Contacta a tu proveedor] [3. 🔌 Usa conexión por cable]"
try:
prompt = f"""
Eres un EXPERTO TÉCNICO en telecomunicaciones. Analiza DETALLADAMENTE estas métricas reales:
📊 MÉTRICAS TÉCNICAS:
• Velocidad de DESCARGA: {download} Mbps
• Velocidad de SUBIDA: {upload} Mbps
• LATENCIA (Ping): {ping} ms
• ESTABILIDAD (Jitter): {jitter} ms
🔍 PROPORCIONA UN ANÁLISIS COMPLETO:
CALIDAD: [Excelente 🌟/Muy Buena ✅/Buena 📶/Regular ⚠️/Limitada 🔴]
ANALISIS: [2-3 líneas con análisis técnico específico para streaming, gaming, teletrabajo]
RECOMENDACIONES: [1. 💡 recomendación práctica] [2. 🚀 optimización técnica] [3. 📞 acción con proveedor]
Sé ESPECÍFICO y PRÁCTICO. Incluye emojis relevantes.
"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.8,
max_tokens=300
)
resultado = response.choices[0].message.content
print(f"✅ IA respuesta: {resultado}")
return resultado
except Exception as e:
print(f"❌ Error OpenAI: {e}")
# Fallback detallado
return f"CALIDAD: Buena 📶\nANALISIS: Conexión estable con {download} Mbps de descarga. Latencia de {ping} ms adecuada para uso general.\nRECOMENDACIONES: [1. 💡 Velocidad suficiente para streaming HD] [2. 📡 Ping aceptable para videollamadas] [3. ⚡ Considera optimizar WiFi]"
def run_test():
"""Ejecuta el test completo"""
# Fase 1: Progreso
yield "🔄 Iniciando test de velocidad...", "", "", "", 0, 0, 0, 0
time.sleep(1)
yield "📡 Conectando con servidores...", "", "", "", 0, 0, 0, 0
time.sleep(1)
yield "⏱️ Midiendo latencia...", "", "", "", 0, 0, 0, 0
time.sleep(1)
yield "🔽 Probando velocidad de descarga...", "", "", "", 0, 0, 0, 0
time.sleep(1)
yield "🔼 Probando velocidad de subida...", "", "", "", 0, 0, 0, 0
time.sleep(1)
yield "🤖 Analizando con IA...", "", "", "", 0, 0, 0, 0
time.sleep(2)
# Obtener resultados
download, upload, ping, jitter = simulate_speed_test()
ai_result = analyze_with_openai(download, upload, ping, jitter)
# Parsear resultado MEJORADO
lines = ai_result.split('\n')
# Buscar cada sección más flexible
calidad = "Buena"
analisis = "Análisis de conexión completado"
recomendaciones = ["💡 Configuración estándar", "📡 Optimización básica"]
for line in lines:
line = line.strip()
if 'CALIDAD:' in line:
calidad = line.replace('CALIDAD:', '').strip()
elif 'ANALISIS:' in line:
analisis = line.replace('ANALISIS:', '').strip()
elif 'RECOMENDACIONES:' in line:
recs_text = line.replace('RECOMENDACIONES:', '').strip()
# Extraer recomendaciones individuales
recomendaciones = re.findall(r'\[[^\]]+\]', recs_text)
if not recomendaciones:
recomendaciones = ["💡 Mantén tu conexión", "🚀 Optimiza configuración"]
# HTML MEJORADO con más detalles
metrics_html = f"""
<div style="background: white; padding: 20px; border-radius: 10px; margin: 10px 0; border: 2px solid #007bff;">
<h2 style="color: black !important; text-align: center;">📊 RESULTADOS DETALLADOS</h2>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #dc3545;">
<h3 style="color: black !important; margin: 0;">⬇️ Descarga</h3>
<p style="font-size: 24px; font-weight: bold; color: #dc3545 !important; margin: 5px 0;">{download} Mbps</p>
<small style="color: #666 !important;">{'🌟 Excelente' if download > 80 else '✅ Buena' if download > 50 else '📶 Aceptable' if download > 25 else '⚠️ Limitada'}</small>
</div>
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="color: black !important; margin: 0;">⬆️ Subida</h3>
<p style="font-size: 24px; font-weight: bold; color: #28a745 !important; margin: 5px 0;">{upload} Mbps</p>
<small style="color: #666 !important;">{'🚀 Rápida' if upload > 20 else '📤 Adecuada' if upload > 10 else '📨 Básica'}</small>
</div>
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #007bff;">
<h3 style="color: black !important; margin: 0;">⏱️ Ping</h3>
<p style="font-size: 24px; font-weight: bold; color: #007bff !important; margin: 5px 0;">{ping} ms</p>
<small style="color: #666 !important;">{'🎮 Ideal gaming' if ping < 30 else '💬 Bueno' if ping < 60 else '📞 Aceptable'}</small>
</div>
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107;">
<h3 style="color: black !important; margin: 0;">📈 Calidad</h3>
<p style="font-size: 20px; font-weight: bold; color: #ffc107 !important; margin: 5px 0;">{calidad}</p>
<small style="color: #666 !important;">Análisis con IA</small>
</div>
</div>
</div>
"""
ai_html = f"""
<div style="background: white; padding: 20px; border-radius: 8px; margin: 10px 0; border: 2px solid #6f42c1;">
<h3 style="color: black !important; margin: 0 0 15px 0;">🧠 ANÁLISIS DE INTELIGENCIA ARTIFICIAL</h3>
<p style="color: black !important; margin: 0; line-height: 1.5; font-size: 15px;">{analisis}</p>
</div>
"""
# HTML para recomendaciones
recs_html = f"""
<div style="background: white; padding: 20px; border-radius: 8px; margin: 10px 0; border: 2px solid #20c997;">
<h3 style="color: black !important; margin: 0 0 15px 0;">💡 RECOMENDACIONES INTELIGENTES</h3>
<div style="display: flex; flex-direction: column; gap: 10px;">
{"".join([f'<div style="background: #f8f9fa; padding: 12px; border-radius: 6px; border-left: 3px solid #20c997;"><p style="color: black !important; margin: 0; font-size: 14px;">{rec}</p></div>' for rec in recomendaciones])}
</div>
</div>
"""
yield "✅ Test completado con análisis detallado", metrics_html, ai_html, recs_html, download, upload, ping, jitter
# INTERFAZ PRINCIPAL
with gr.Blocks(css=CSS_FIJO, theme=gr.themes.Base()) as demo:
# HEADER
gr.HTML("""
<div style="text-align: center; background: white; padding: 20px; border-bottom: 3px solid #007bff;">
<h1 style="color: black !important; margin: 0; font-size: 28px;">🚀 PinGoo</h1>
<p style="color: black !important; margin: 5px 0; font-size: 20px;">Test de Velocidad con IA</p>
<p style="color: #666 !important; margin: 0; font-size: 14px;">💡 PinGoo mide la calidad, no solo la cantidad.</p>
</div>
""")
with gr.Row():
btn = gr.Button("🧠 INICIAR TEST", variant="primary", size="lg")
status = gr.Markdown("👉 Tip: Para que la medición sea más exacta, pausa actualizaciones, descargas o streaming en otros dispositivos de tu Red Lan.")
metrics = gr.HTML()
analysis = gr.HTML()
recs = gr.HTML()
# Métricas ocultas
d_metric = gr.Number(visible=False)
u_metric = gr.Number(visible=False)
p_metric = gr.Number(visible=False)
j_metric = gr.Number(visible=False)
# FOOTER
gr.HTML("""
<div style="text-align: center; background: white; padding: 15px; margin-top: 20px; border-top: 2px solid #f0f0f0;">
<p style="color: black !important; margin: 5px 0;">🔧 Tecnología: Python + Gradio + OpenAI</p>
<p style="color: black !important; margin: 5px 0;">🌐 Desarrollado para <strong style="color: #007bff !important;">DoctorLinux.com</strong></p>
</div>
""")
btn.click(
run_test,
outputs=[status, metrics, analysis, recs, d_metric, u_metric, p_metric, j_metric]
)
if __name__ == "__main__":
demo.launch() |