waqasbm's picture
Update app.py
b1dbecf verified
import streamlit as st
import speedtest
import time
import pandas as pd
from datetime import datetime
import requests
import os
# ========== PAGE CONFIG ==========
st.set_page_config(page_title="AI-Powered Speed Test", layout="centered")
# Dark theme
st.markdown("""
<style>
body { background-color: #111827; color: #f9fafb; }
.stButton>button { background-color: #2563eb; color: white; border-radius: 10px; }
</style>
""", unsafe_allow_html=True)
st.title("πŸ“Ά Internet Speed Test + 🧠 AI Network Advisor")
# ========== PUBLIC IP ==========
def get_public_ip():
try:
res = requests.get("https://api.ipify.org?format=json", timeout=5)
return res.json().get("ip", "Unavailable")
except:
return "Unavailable"
st.markdown(f"🌍 **Your Public IP:** `{get_public_ip()}`")
# ========== SESSION STATE ==========
if "history" not in st.session_state:
st.session_state.history = []
if "last_test" not in st.session_state:
st.session_state.last_test = 0
# ========== GROQ AI FUNCTION ==========
def analyze_with_groq(download, upload, latency):
api_key = os.getenv("speedtest")
if not api_key:
return "⚠️ GROQ API key not set."
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
prompt = (
f"My internet speed is:\n"
f"πŸ“₯ Download: {download} Mbps\n"
f"πŸ“€ Upload : {upload} Mbps\n"
f"⏱️ Latency : {latency} sec\n\n"
"What online tasks (e.g., Zoom, gaming, streaming) can I perform smoothly with this connection?"
)
payload = {
"model": "llama3-8b-8192",
"messages": [{"role": "user", "content": prompt}]
}
try:
res = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=payload)
if res.status_code == 200:
return res.json()["choices"][0]["message"]["content"]
else:
return f"❌ GROQ Error: {res.status_code} - {res.text}"
except Exception as e:
return f"❌ Failed to connect to GROQ: {e}"
# ========== SPEED TEST FUNCTION ==========
def run_speed_test():
stt = speedtest.Speedtest()
stt.get_best_server()
start = time.time()
download = stt.download()
upload = stt.upload()
end = time.time()
download_mbps = round(download / 1_000_000, 2)
upload_mbps = round(upload / 1_000_000, 2)
test_time_sec = round(end - start, 2)
result = {
"Timestamp": datetime.now().strftime("%H:%M:%S"),
"Download (Mbps)": download_mbps,
"Upload (Mbps)": upload_mbps,
"Time (s)": test_time_sec,
}
st.session_state.history.append(result)
st.session_state.last_test = time.time()
st.success("βœ… Test complete!")
st.markdown(f"**πŸ“₯ Download:** `{download_mbps} Mbps`")
st.markdown(f"**πŸ“€ Upload :** `{upload_mbps} Mbps`")
st.markdown(f"**⏱️ Time :** `{test_time_sec} sec`")
st.markdown("### 🧠 GROQ AI Evaluation:")
with st.spinner("Asking GROQ AI..."):
groq_response = analyze_with_groq(download_mbps, upload_mbps, test_time_sec)
st.info(groq_response)
# ========== RETEST SETUP ==========
interval = st.selectbox("⏱️ Retest every (minutes)", [0, 1, 5, 10, 15, 30, 60], index=0)
auto_retest = interval > 0
# ========== RUN TEST BUTTON ==========
if st.button("▢️ Start Speed Test"):
with st.spinner("Running speed test..."):
try:
run_speed_test()
except Exception as e:
st.error(f"❌ Speed test failed: {e}")
# ========== AUTO RETEST ==========
if auto_retest:
now = time.time()
if now - st.session_state.last_test > interval * 60:
with st.spinner("Auto-retesting..."):
try:
run_speed_test()
except Exception as e:
st.error(f"❌ Auto test failed: {e}")
# ========== HISTORY ==========
if st.session_state.history:
st.markdown("---")
st.subheader("πŸ“Š Test History")
df = pd.DataFrame(st.session_state.history)
st.line_chart(df[["Download (Mbps)", "Upload (Mbps)"]])
with st.expander("πŸ“‹ Full results"):
st.dataframe(df, use_container_width=True)