GamerC0der commited on
Commit
74aec27
·
verified ·
1 Parent(s): 02a9cb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -111
app.py CHANGED
@@ -1,111 +1,56 @@
1
- from flask import Flask, request, Response
2
- from urllib.parse import urlparse
3
- import json, os, subprocess, threading
4
-
5
- app = Flask(__name__)
6
-
7
- INDEX = """<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Website Image</title></head><body><form id="f"><input id="u" name="url" placeholder="https://example.com"><button type="submit">Go</button></form><div><img id="img" alt=""></div><pre id="e"></pre><script>
8
- const f=document.getElementById('f'),u=document.getElementById('u'),img=document.getElementById('img'),e=document.getElementById('e');
9
- f.addEventListener('submit',async(ev)=>{ev.preventDefault();e.textContent='';img.removeAttribute('src');
10
- const url=u.value.trim(); if(!url){e.textContent='Missing URL';return;}
11
- const api='/api/?url='+encodeURIComponent(url)+'&t='+Date.now();
12
- try{
13
- const r=await fetch(api);
14
- const ct=(r.headers.get('content-type')||'');
15
- if(!r.ok){
16
- if(ct.includes('application/json')){const j=await r.json();e.textContent=j.error||('HTTP '+r.status);}
17
- else{e.textContent='HTTP '+r.status;}
18
- return;
19
- }
20
- img.src=api;
21
- }catch(err){e.textContent=String(err);}
22
- });
23
- </script></body></html>"""
24
-
25
- _install_lock = threading.Lock()
26
- _checked = False
27
-
28
- def normalize(raw: str) -> str:
29
- raw = (raw or "").strip()
30
- if not raw:
31
- raise ValueError("Missing URL")
32
- if not (raw.startswith("http://") or raw.startswith("https://")):
33
- raw = "https://" + raw
34
- p = urlparse(raw)
35
- if p.scheme not in ("http", "https") or not p.netloc:
36
- raise ValueError("Invalid URL")
37
- return raw
38
-
39
- def _run_install(cmd: list[str]) -> None:
40
- env = os.environ.copy()
41
- env.setdefault("PLAYWRIGHT_BROWSERS_PATH", "0")
42
- subprocess.run(
43
- cmd,
44
- env=env,
45
- stdout=subprocess.PIPE,
46
- stderr=subprocess.STDOUT,
47
- text=True,
48
- check=True,
49
- )
50
-
51
- def ensure_browsers_installed() -> None:
52
- global _checked
53
- if _checked:
54
- return
55
- with _install_lock:
56
- if _checked:
57
- return
58
- try:
59
- _run_install(["playwright", "install", "--with-deps", "chromium"])
60
- except Exception:
61
- try:
62
- _run_install(["python", "-m", "playwright", "install", "--with-deps", "chromium"])
63
- except Exception:
64
- _run_install(["python", "-m", "playwright", "install", "chromium"])
65
- _checked = True
66
-
67
- def screenshot(url: str) -> bytes:
68
- ensure_browsers_installed()
69
- from playwright.sync_api import sync_playwright
70
- with sync_playwright() as pw:
71
- browser = pw.chromium.launch(headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"])
72
- try:
73
- page = browser.new_page(viewport={"width": 1280, "height": 720})
74
- page.set_default_navigation_timeout(45000)
75
- page.set_default_timeout(45000)
76
- try:
77
- page.goto(url, wait_until="networkidle")
78
- except Exception:
79
- page.goto(url, wait_until="domcontentloaded")
80
- try:
81
- page.wait_for_load_state("networkidle", timeout=5000)
82
- except Exception:
83
- pass
84
- page.wait_for_timeout(600)
85
- return page.screenshot(full_page=True, type="png")
86
- finally:
87
- try:
88
- browser.close()
89
- except Exception:
90
- pass
91
-
92
- @app.get("/")
93
- def home():
94
- return Response(INDEX, mimetype="text/html; charset=utf-8")
95
-
96
- @app.get("/api/")
97
- def api():
98
- try:
99
- url = normalize(request.args.get("url", ""))
100
- png = screenshot(url)
101
- return Response(png, mimetype="image/png")
102
- except ValueError as e:
103
- return Response(json.dumps({"error": str(e)}), status=400, mimetype="application/json")
104
- except subprocess.CalledProcessError as e:
105
- out = (e.stdout or "").strip()
106
- return Response(json.dumps({"error": out or "Playwright install failed"}), status=500, mimetype="application/json")
107
- except Exception as e:
108
- return Response(json.dumps({"error": f"{type(e).__name__}: {e}"}), status=502, mimetype="application/json")
109
-
110
- if __name__ == "__main__":
111
- app.run(host="0.0.0.0", port=7860, debug=True)
 
1
+ import http.server
2
+ import socketserver
3
+ import json
4
+ from curl_cffi import requests
5
+
6
+ PORT = 7860
7
+ URL = "https://multi-modal.ai.cloudflare.com/api/inference?model=@cf/deepgram/nova-3&field=audio"
8
+
9
+ HTML = """
10
+ <!DOCTYPE html>
11
+ <html>
12
+ <body>
13
+ <h1>Nova-3 Playground</h1>
14
+ <input type="file" id="f" accept="audio/mpeg">
15
+ <button onclick="u()">Transcribe</button>
16
+ <p>Status: <span id="s">Idle</span></p>
17
+ <pre id="r" style="background:#eee;padding:10px"></pre>
18
+ <script>
19
+ async function u() {
20
+ const f = document.getElementById('f').files[0];
21
+ if(!f) return;
22
+ document.getElementById('s').innerText = "Processing...";
23
+ try {
24
+ const res = await fetch('/api', { method: 'POST', body: f });
25
+ const data = await res.json();
26
+ document.getElementById('r').innerText = JSON.stringify(data, null, 2);
27
+ document.getElementById('s').innerText = "Done";
28
+ } catch(e) {
29
+ document.getElementById('s').innerText = "Error";
30
+ }
31
+ }
32
+ </script>
33
+ </body>
34
+ </html>
35
+ """
36
+
37
+ class Handler(http.server.BaseHTTPRequestHandler):
38
+ def do_GET(self):
39
+ self.send_response(200)
40
+ self.send_header("Content-type", "text/html")
41
+ self.end_headers()
42
+ self.wfile.write(HTML.encode())
43
+
44
+ def do_POST(self):
45
+ if self.path == '/api':
46
+ length = int(self.headers['Content-Length'])
47
+ body = self.rfile.read(length)
48
+ r = requests.post(URL, content=body, impersonate="chrome")
49
+ self.send_response(200)
50
+ self.send_header("Content-type", "application/json")
51
+ self.end_headers()
52
+ self.wfile.write(r.content)
53
+
54
+ with socketserver.TCPServer(("", PORT), Handler) as d:
55
+ print(f"Server: {PORT}")
56
+ d.serve_forever()