File size: 6,035 Bytes
b2cff8f
 
5f018aa
 
 
 
b2cff8f
 
5f018aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2cff8f
5f018aa
 
 
 
 
 
 
 
 
 
b2cff8f
5f018aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2cff8f
5f018aa
 
 
 
b2cff8f
5f018aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2cff8f
 
5f018aa
b2cff8f
5f018aa
 
 
b2cff8f
 
5f018aa
 
 
 
 
 
b2cff8f
5f018aa
 
 
 
 
 
 
 
 
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
# app.py

from flask import Flask, send_file, request, jsonify, Response
import io, os, random
import threading
import time
import gradio as gr

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# Minimal Flask backend for LibreSpeed-style tests
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

app = Flask(__name__)

# Pre-generate a 10 MiB random blob for download tests
DOWNLOAD_SIZE_BYTES = 10 * 1024 * 1024  # 10 MiB

# We generate once at startup to avoid repeated overhead
_random_blob = os.urandom(DOWNLOAD_SIZE_BYTES)

@app.route("/download_test")
def download_test():
    """
    Serve a fixed-size blob (10 MiB) to the client for download‐speed measurement.
    """
    return Response(
        _random_blob,
        mimetype="application/octet-stream",
        headers={
            "Content-Disposition": f"attachment; filename=\"test_{DOWNLOAD_SIZE_BYTES}.bin\""
        }
    )

@app.route("/upload_test", methods=["POST"])
def upload_test():
    """
    Accept arbitrary data from client. Return immediately with length for timing.
    """
    data = request.get_data()
    size = len(data)  # bytes received
    # We don’t store it; this endpoint exists purely to let the JS measure upload speed.
    return jsonify({"received_bytes": size})

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# HTML/JS frontend (embedded LibreSpeed logic)
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

LIBRESPEED_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Client-Side Speed Test</title>
  <style>
    body { font-family: sans-serif; max-width: 600px; margin: 2em auto; }
    button { padding: 0.5em 1em; font-size: 1rem; }
    .result { margin-top: 1.5em; }
    .label { font-weight: bold; }
  </style>
</head>
<body>
  <h2>Wi-Fi / Ethernet Speed Test (Client-Side)</h2>
  <p>This test will measure your real Internet speed by downloading a 10 MiB file and uploading random data.</p>
  <button id="startBtn">Start Speed Test</button>

  <div class="result" id="results" style="display: none;">
    <p><span class="label">Download Speed:</span> <span id="dlSpeed">–</span></p>
    <p><span class="label">Upload Speed:</span> <span id="ulSpeed">–</span></p>
    <p><span class="label">Ping:</span> <span id="ping">–</span></p>
  </div>

  <script>
    const startBtn = document.getElementById("startBtn");
    const resultsDiv = document.getElementById("results");
    const dlSpan = document.getElementById("dlSpeed");
    const ulSpan = document.getElementById("ulSpeed");
    const pingSpan = document.getElementById("ping");

    // Utility to format bits/sec β†’ Mbps
    function toMbps(bits) {
      return (bits / 1e6).toFixed(2) + " Mbps";
    }

    startBtn.addEventListener("click", async () => {
      startBtn.disabled = true;
      resultsDiv.style.display = "block";
      dlSpan.textContent = "Testing...";
      ulSpan.textContent = "Testing...";
      pingSpan.textContent = "Testing...";

      // 1) Measure ping by sending a tiny GET
      let pingTimes = [];
      for (let i = 0; i < 5; i++) {
        const t0 = performance.now();
        await fetch("/ping_test?t=" + i, { cache: "no-store" });
        const t1 = performance.now();
        pingTimes.push(t1 - t0);
      }
      const avgPing = pingTimes.reduce((a, b) => a + b, 0) / pingTimes.length;
      pingSpan.textContent = avgPing.toFixed(2) + " ms";

      // 2) Download test: fetch the 10 MiB blob, measure duration
      const dlUrl = "/download_test";
      const dlStart = performance.now();
      const response = await fetch(dlUrl, { cache: "no-store" });
      const blob = await response.blob();
      const dlEnd = performance.now();
      const dlBytes = blob.size;
      const dlBits = dlBytes * 8;
      const dlDurationSec = (dlEnd - dlStart) / 1000;
      const dlSpeedBps = dlBits / dlDurationSec; // bits/sec
      dlSpan.textContent = toMbps(dlSpeedBps);

      // 3) Upload test: send a random ArrayBuffer of same size (10 MiB) to /upload_test
      //    We reuse the DownloadSize for symmetry. In real tests, you might want a smaller upload blob.
      const uploadSizeBytes = dlBytes;
      // Generate random bytes
      const randomBuffer = new Uint8Array(uploadSizeBytes);
      window.crypto.getRandomValues(randomBuffer);

      const ulStart = performance.now();
      await fetch("/upload_test", {
        method: "POST",
        headers: { "Content-Type": "application/octet-stream" },
        body: randomBuffer
      });
      const ulEnd = performance.now();
      const ulDurationSec = (ulEnd - ulStart) / 1000;
      const ulBits = uploadSizeBytes * 8;
      const ulSpeedBps = ulBits / ulDurationSec;
      ulSpan.textContent = toMbps(ulSpeedBps);

      startBtn.disabled = false;
    });
  </script>
</body>
</html>
"""

# Expose the HTML through Gradio’s Interface
def serve_html():
    return LIBRESPEED_HTML

iface = gr.Interface(
    fn=serve_html,
    inputs=[],
    outputs=gr.HTML(label="Speed Test"),
    title="Client-Side Speed Test",
    description="Measures your actual Internet link (download/upload/ping) via JavaScript."
)

def gradio_thread():
    """
    Run Gradio in a thread so that Flask and Gradio both serve on the same port.
    """
    iface.launch(server_name="0.0.0.0", server_port=7860, share=False)

if __name__ == "__main__":
    # 1) Start Gradio in a background thread
    t = threading.Thread(target=gradio_thread, daemon=True)
    t.start()

    # 2) Start Flask to serve endpoints (on port 7860 as well)
    #    Since Gradio’s Flask is already bound, we just add our routes to the same server.
    #    Gradio uses Flask under the hood, so these routes will be served automatically.
    #    (In recent Gradio versions, custom @app routes work if we set `allow_flagging="never"`, etc.)
    app.run(host="0.0.0.0", port=7860, debug=False)