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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import time
|
| 3 |
+
import random
|
| 4 |
+
import openai
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
# Configuración OpenAI
|
| 9 |
+
try:
|
| 10 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
if api_key and api_key.startswith("sk-"):
|
| 12 |
+
client = openai.OpenAI(api_key=api_key)
|
| 13 |
+
AI_ENABLED = True
|
| 14 |
+
print("✅ OpenAI configurado correctamente")
|
| 15 |
+
else:
|
| 16 |
+
client = None
|
| 17 |
+
AI_ENABLED = False
|
| 18 |
+
print("⚠️ Usando análisis automático (sin OpenAI)")
|
| 19 |
+
except Exception as e:
|
| 20 |
+
client = None
|
| 21 |
+
AI_ENABLED = False
|
| 22 |
+
print(f"⚠️ Error OpenAI: {e}")
|
| 23 |
+
|
| 24 |
+
# CSS FIJO - FUNCIONA EN MODO CLARO Y OSCURO
|
| 25 |
+
CSS_FIJO = """
|
| 26 |
+
.gradio-container, body, .markdown, .prose, .gr-box, .gr-form, .gr-button,
|
| 27 |
+
.gr-textbox, .gr-html, .gr-markdown {
|
| 28 |
+
color: #000000 !important;
|
| 29 |
+
background: #ffffff !important;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
h1, h2, h3, h4, h5, h6, p, span, div, label {
|
| 33 |
+
color: #000000 !important;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
button {
|
| 37 |
+
color: #000000 !important;
|
| 38 |
+
border: 2px solid #007bff !important;
|
| 39 |
+
background: #f8f9fa !important;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
button:hover {
|
| 43 |
+
background: #007bff !important;
|
| 44 |
+
color: #ffffff !important;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
.gr-container, .panel, .block, .container {
|
| 48 |
+
background: #ffffff !important;
|
| 49 |
+
color: #000000 !important;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
* {
|
| 53 |
+
color: #000000 !important;
|
| 54 |
+
}
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def simulate_speed_test():
|
| 58 |
+
"""Simula métricas de velocidad realistas"""
|
| 59 |
+
download = round(random.uniform(10, 100), 2)
|
| 60 |
+
upload = round(random.uniform(5, 50), 2)
|
| 61 |
+
ping = round(random.uniform(15, 80), 2)
|
| 62 |
+
jitter = round(random.uniform(1, 10), 2)
|
| 63 |
+
return download, upload, ping, jitter
|
| 64 |
+
|
| 65 |
+
def analyze_with_openai(download, upload, ping, jitter):
|
| 66 |
+
"""Análisis con OpenAI MEJORADO - respuestas más detalladas"""
|
| 67 |
+
if not AI_ENABLED:
|
| 68 |
+
# Fallback más detallado
|
| 69 |
+
if download > 80:
|
| 70 |
+
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]"
|
| 71 |
+
elif download > 50:
|
| 72 |
+
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]"
|
| 73 |
+
elif download > 25:
|
| 74 |
+
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]"
|
| 75 |
+
else:
|
| 76 |
+
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]"
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
prompt = f"""
|
| 80 |
+
Eres un EXPERTO TÉCNICO en telecomunicaciones. Analiza DETALLADAMENTE estas métricas reales:
|
| 81 |
+
|
| 82 |
+
📊 MÉTRICAS TÉCNICAS:
|
| 83 |
+
• Velocidad de DESCARGA: {download} Mbps
|
| 84 |
+
• Velocidad de SUBIDA: {upload} Mbps
|
| 85 |
+
• LATENCIA (Ping): {ping} ms
|
| 86 |
+
• ESTABILIDAD (Jitter): {jitter} ms
|
| 87 |
+
|
| 88 |
+
🔍 PROPORCIONA UN ANÁLISIS COMPLETO:
|
| 89 |
+
|
| 90 |
+
CALIDAD: [Excelente 🌟/Muy Buena ✅/Buena 📶/Regular ⚠️/Limitada 🔴]
|
| 91 |
+
ANALISIS: [2-3 líneas con análisis técnico específico para streaming, gaming, teletrabajo]
|
| 92 |
+
RECOMENDACIONES: [1. 💡 recomendación práctica] [2. 🚀 optimización técnica] [3. 📞 acción con proveedor]
|
| 93 |
+
|
| 94 |
+
Sé ESPECÍFICO y PRÁCTICO. Incluye emojis relevantes.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
response = client.chat.completions.create(
|
| 98 |
+
model="gpt-3.5-turbo",
|
| 99 |
+
messages=[{"role": "user", "content": prompt}],
|
| 100 |
+
temperature=0.8,
|
| 101 |
+
max_tokens=300
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
resultado = response.choices[0].message.content
|
| 105 |
+
print(f"✅ IA respuesta: {resultado}")
|
| 106 |
+
return resultado
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"❌ Error OpenAI: {e}")
|
| 110 |
+
# Fallback detallado
|
| 111 |
+
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]"
|
| 112 |
+
|
| 113 |
+
def run_test():
|
| 114 |
+
"""Ejecuta el test completo"""
|
| 115 |
+
# Fase 1: Progreso
|
| 116 |
+
yield "🔄 Iniciando test de velocidad...", "", "", "", 0, 0, 0, 0
|
| 117 |
+
time.sleep(1)
|
| 118 |
+
|
| 119 |
+
yield "📡 Conectando con servidores...", "", "", "", 0, 0, 0, 0
|
| 120 |
+
time.sleep(1)
|
| 121 |
+
|
| 122 |
+
yield "⏱️ Midiendo latencia...", "", "", "", 0, 0, 0, 0
|
| 123 |
+
time.sleep(1)
|
| 124 |
+
|
| 125 |
+
yield "🔽 Probando velocidad de descarga...", "", "", "", 0, 0, 0, 0
|
| 126 |
+
time.sleep(1)
|
| 127 |
+
|
| 128 |
+
yield "🔼 Probando velocidad de subida...", "", "", "", 0, 0, 0, 0
|
| 129 |
+
time.sleep(1)
|
| 130 |
+
|
| 131 |
+
yield "🤖 Analizando con IA...", "", "", "", 0, 0, 0, 0
|
| 132 |
+
time.sleep(2)
|
| 133 |
+
|
| 134 |
+
# Obtener resultados
|
| 135 |
+
download, upload, ping, jitter = simulate_speed_test()
|
| 136 |
+
ai_result = analyze_with_openai(download, upload, ping, jitter)
|
| 137 |
+
|
| 138 |
+
# Parsear resultado MEJORADO
|
| 139 |
+
lines = ai_result.split('\n')
|
| 140 |
+
|
| 141 |
+
# Buscar cada sección más flexible
|
| 142 |
+
calidad = "Buena"
|
| 143 |
+
analisis = "Análisis de conexión completado"
|
| 144 |
+
recomendaciones = ["💡 Configuración estándar", "📡 Optimización básica"]
|
| 145 |
+
|
| 146 |
+
for line in lines:
|
| 147 |
+
line = line.strip()
|
| 148 |
+
if 'CALIDAD:' in line:
|
| 149 |
+
calidad = line.replace('CALIDAD:', '').strip()
|
| 150 |
+
elif 'ANALISIS:' in line:
|
| 151 |
+
analisis = line.replace('ANALISIS:', '').strip()
|
| 152 |
+
elif 'RECOMENDACIONES:' in line:
|
| 153 |
+
recs_text = line.replace('RECOMENDACIONES:', '').strip()
|
| 154 |
+
# Extraer recomendaciones individuales
|
| 155 |
+
recomendaciones = re.findall(r'\[[^\]]+\]', recs_text)
|
| 156 |
+
if not recomendaciones:
|
| 157 |
+
recomendaciones = ["💡 Mantén tu conexión", "🚀 Optimiza configuración"]
|
| 158 |
+
|
| 159 |
+
# HTML MEJORADO con más detalles
|
| 160 |
+
metrics_html = f"""
|
| 161 |
+
<div style="background: white; padding: 20px; border-radius: 10px; margin: 10px 0; border: 2px solid #007bff;">
|
| 162 |
+
<h2 style="color: black !important; text-align: center;">📊 RESULTADOS DETALLADOS</h2>
|
| 163 |
+
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
|
| 164 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #dc3545;">
|
| 165 |
+
<h3 style="color: black !important; margin: 0;">⬇️ Descarga</h3>
|
| 166 |
+
<p style="font-size: 24px; font-weight: bold; color: #dc3545 !important; margin: 5px 0;">{download} Mbps</p>
|
| 167 |
+
<small style="color: #666 !important;">{'🌟 Excelente' if download > 80 else '✅ Buena' if download > 50 else '📶 Aceptable' if download > 25 else '⚠️ Limitada'}</small>
|
| 168 |
+
</div>
|
| 169 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #28a745;">
|
| 170 |
+
<h3 style="color: black !important; margin: 0;">⬆️ Subida</h3>
|
| 171 |
+
<p style="font-size: 24px; font-weight: bold; color: #28a745 !important; margin: 5px 0;">{upload} Mbps</p>
|
| 172 |
+
<small style="color: #666 !important;">{'🚀 Rápida' if upload > 20 else '📤 Adecuada' if upload > 10 else '📨 Básica'}</small>
|
| 173 |
+
</div>
|
| 174 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #007bff;">
|
| 175 |
+
<h3 style="color: black !important; margin: 0;">⏱️ Ping</h3>
|
| 176 |
+
<p style="font-size: 24px; font-weight: bold; color: #007bff !important; margin: 5px 0;">{ping} ms</p>
|
| 177 |
+
<small style="color: #666 !important;">{'🎮 Ideal gaming' if ping < 30 else '💬 Bueno' if ping < 60 else '📞 Aceptable'}</small>
|
| 178 |
+
</div>
|
| 179 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107;">
|
| 180 |
+
<h3 style="color: black !important; margin: 0;">📈 Calidad</h3>
|
| 181 |
+
<p style="font-size: 20px; font-weight: bold; color: #ffc107 !important; margin: 5px 0;">{calidad}</p>
|
| 182 |
+
<small style="color: #666 !important;">Análisis con IA</small>
|
| 183 |
+
</div>
|
| 184 |
+
</div>
|
| 185 |
+
</div>
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
ai_html = f"""
|
| 189 |
+
<div style="background: white; padding: 20px; border-radius: 8px; margin: 10px 0; border: 2px solid #6f42c1;">
|
| 190 |
+
<h3 style="color: black !important; margin: 0 0 15px 0;">🧠 ANÁLISIS DE INTELIGENCIA ARTIFICIAL</h3>
|
| 191 |
+
<p style="color: black !important; margin: 0; line-height: 1.5; font-size: 15px;">{analisis}</p>
|
| 192 |
+
</div>
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
# HTML para recomendaciones
|
| 196 |
+
recs_html = f"""
|
| 197 |
+
<div style="background: white; padding: 20px; border-radius: 8px; margin: 10px 0; border: 2px solid #20c997;">
|
| 198 |
+
<h3 style="color: black !important; margin: 0 0 15px 0;">💡 RECOMENDACIONES INTELIGENTES</h3>
|
| 199 |
+
<div style="display: flex; flex-direction: column; gap: 10px;">
|
| 200 |
+
{"".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])}
|
| 201 |
+
</div>
|
| 202 |
+
</div>
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
yield "✅ Test completado con análisis detallado", metrics_html, ai_html, recs_html, download, upload, ping, jitter
|
| 206 |
+
|
| 207 |
+
# INTERFAZ PRINCIPAL
|
| 208 |
+
with gr.Blocks(css=CSS_FIJO, theme=gr.themes.Base()) as demo:
|
| 209 |
+
|
| 210 |
+
# HEADER
|
| 211 |
+
gr.HTML("""
|
| 212 |
+
<div style="text-align: center; background: white; padding: 20px; border-bottom: 3px solid #007bff;">
|
| 213 |
+
<h1 style="color: black !important; margin: 0; font-size: 28px;">🚀 TEST DE VELOCIDAD CON IA</h1>
|
| 214 |
+
<p style="color: black !important; margin: 5px 0; font-size: 16px;">DoctorLinux.com - Análisis Inteligente</p>
|
| 215 |
+
<p style="color: #666 !important; margin: 0; font-size: 14px;">Texto visible en todos los navegadores</p>
|
| 216 |
+
</div>
|
| 217 |
+
""")
|
| 218 |
+
|
| 219 |
+
with gr.Row():
|
| 220 |
+
btn = gr.Button("🧠 INICIAR TEST CON IA", variant="primary", size="lg")
|
| 221 |
+
|
| 222 |
+
status = gr.Markdown("**Presiona el botón para comenzar**")
|
| 223 |
+
metrics = gr.HTML()
|
| 224 |
+
analysis = gr.HTML()
|
| 225 |
+
recs = gr.HTML()
|
| 226 |
+
|
| 227 |
+
# Métricas ocultas
|
| 228 |
+
d_metric = gr.Number(visible=False)
|
| 229 |
+
u_metric = gr.Number(visible=False)
|
| 230 |
+
p_metric = gr.Number(visible=False)
|
| 231 |
+
j_metric = gr.Number(visible=False)
|
| 232 |
+
|
| 233 |
+
# FOOTER
|
| 234 |
+
gr.HTML("""
|
| 235 |
+
<div style="text-align: center; background: white; padding: 15px; margin-top: 20px; border-top: 2px solid #f0f0f0;">
|
| 236 |
+
<p style="color: black !important; margin: 5px 0;">🔧 Tecnología: Python + Gradio + OpenAI</p>
|
| 237 |
+
<p style="color: black !important; margin: 5px 0;">🌐 Desarrollado para <strong style="color: #007bff !important;">DoctorLinux.com</strong></p>
|
| 238 |
+
</div>
|
| 239 |
+
""")
|
| 240 |
+
|
| 241 |
+
btn.click(
|
| 242 |
+
run_test,
|
| 243 |
+
outputs=[status, metrics, analysis, recs, d_metric, u_metric, p_metric, j_metric]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
demo.launch()
|