speedtest-ai / app.py
doctorlinux's picture
Update app.py
7dda575 verified
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()