Siddharth Ravikumar commited on
Commit
287e21d
Β·
1 Parent(s): fe740a0

Add HF token for ZeroGPU auth

Browse files
backend/app/api/routes.py CHANGED
@@ -28,6 +28,16 @@ logger = get_logger("api")
28
  router = APIRouter(prefix="/api")
29
 
30
 
 
 
 
 
 
 
 
 
 
 
31
  # ── Health ─────────────────────────────────────────────────────────────
32
 
33
  @router.get("/health")
 
28
  router = APIRouter(prefix="/api")
29
 
30
 
31
+ # ── Config ─────────────────────────────────────────────────────────────
32
+
33
+ @router.get("/config")
34
+ async def get_config():
35
+ """Return backend configuration to the frontend (e.g. HF_TOKEN for ZeroGPU)."""
36
+ return {
37
+ "hf_token": os.environ.get("HF_TOKEN", "")
38
+ }
39
+
40
+
41
  # ── Health ─────────────────────────────────────────────────────────────
42
 
43
  @router.get("/health")
debug_analysis.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from app import run_analysis_fn, create_case_fn, upload_photos_fn, ensure_init
3
+ from backend.app.db.database import db
4
+
5
+ async def setup():
6
+ ensure_init()
7
+ # Create a case
8
+ msg, _ = create_case_fn("TEST-001", "Officer John", "NYC", "2023-01-01", "Notes")
9
+ # Add a mock photo
10
+ import os
11
+ from PIL import Image
12
+ os.makedirs("test_photos", exist_ok=True)
13
+ img_path = "test_photos/mock.jpg"
14
+ Image.new("RGB", (100, 100)).save(img_path)
15
+
16
+ # upload
17
+ upload_photos_fn(1, [img_path])
18
+
19
+ # Run analysis
20
+ try:
21
+ res = run_analysis_fn(1)
22
+ print("Analysis result:", res)
23
+ except Exception as e:
24
+ print("Error during analysis:", e)
25
+ import traceback
26
+ traceback.print_exc()
27
+
28
+ if __name__ == "__main__":
29
+ asyncio.run(setup())
frontend/js/alt_app.js CHANGED
@@ -22,10 +22,27 @@ let additionalFiles = []; // For add photos modal
22
  async function callGradioApi(apiName, dataArr) {
23
  const GRADIO_API = '/gradio_api/call/';
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  // Step 1: POST to queue the job
26
  const res = await fetch(GRADIO_API + apiName, {
27
  method: 'POST',
28
- headers: { 'Content-Type': 'application/json' },
29
  credentials: 'include',
30
  body: JSON.stringify({ data: dataArr })
31
  });
@@ -40,9 +57,14 @@ async function callGradioApi(apiName, dataArr) {
40
  // Step 2: Stream the result via fetch (not EventSource)
41
  const streamUrl = GRADIO_API + apiName + '/' + eventId;
42
 
 
 
 
 
 
43
  const sseRes = await fetch(streamUrl, {
44
  method: 'GET',
45
- headers: { 'Accept': 'text/event-stream' },
46
  credentials: 'include',
47
  cache: 'no-cache',
48
  });
 
22
  async function callGradioApi(apiName, dataArr) {
23
  const GRADIO_API = '/gradio_api/call/';
24
 
25
+ // Fetch config to get Hugging Face Token for ZeroGPU authentication
26
+ let hfToken = '';
27
+ try {
28
+ const confRes = await fetch(`${API_BASE}/config`);
29
+ if (confRes.ok) {
30
+ const confData = await confRes.json();
31
+ hfToken = confData.hf_token || '';
32
+ }
33
+ } catch (e) {
34
+ console.warn('Failed to fetch config', e);
35
+ }
36
+
37
+ const headers = { 'Content-Type': 'application/json' };
38
+ if (hfToken) {
39
+ headers['Authorization'] = `Bearer ${hfToken}`;
40
+ }
41
+
42
  // Step 1: POST to queue the job
43
  const res = await fetch(GRADIO_API + apiName, {
44
  method: 'POST',
45
+ headers: headers,
46
  credentials: 'include',
47
  body: JSON.stringify({ data: dataArr })
48
  });
 
57
  // Step 2: Stream the result via fetch (not EventSource)
58
  const streamUrl = GRADIO_API + apiName + '/' + eventId;
59
 
60
+ const streamHeaders = { 'Accept': 'text/event-stream' };
61
+ if (hfToken) {
62
+ streamHeaders['Authorization'] = `Bearer ${hfToken}`;
63
+ }
64
+
65
  const sseRes = await fetch(streamUrl, {
66
  method: 'GET',
67
+ headers: streamHeaders,
68
  credentials: 'include',
69
  cache: 'no-cache',
70
  });
frontend/js/app.js CHANGED
@@ -631,39 +631,7 @@ function renderFaultAnalysis(fault, parties) {
631
 
632
  // ── Run Analysis ──────────────────────────────────────────────────────
633
 
634
- async function runAnalysis() {
635
- if (!currentCaseId) return;
636
-
637
- const overlay = document.getElementById('analysis-overlay');
638
- const stepEl = document.getElementById('analysis-step');
639
- const detailEl = document.getElementById('analysis-detail');
640
-
641
- overlay.classList.remove('hidden');
642
- stepEl.textContent = 'Analyzing accident scene photos...';
643
- detailEl.textContent = 'Running AI vision analysis on each photo. This may take several minutes.';
644
 
645
- try {
646
- const resp = await fetch(`${API_BASE}/cases/${currentCaseId}/analyze`, {
647
- method: 'POST',
648
- });
649
-
650
- if (!resp.ok) {
651
- const err = await resp.json();
652
- throw new Error(err.detail || 'Analysis failed');
653
- }
654
-
655
- const data = await resp.json();
656
- overlay.classList.add('hidden');
657
- showToast(`Analysis complete: ${data.violations_found} violations found`, 'success');
658
-
659
- // Reload case detail
660
- openCase(currentCaseId);
661
-
662
- } catch (e) {
663
- overlay.classList.add('hidden');
664
- showToast(`Analysis failed: ${e.message}`, 'error');
665
- }
666
- }
667
 
668
  // ── Report ────────────────────────────────────────────────────────────
669
 
 
631
 
632
  // ── Run Analysis ──────────────────────────────────────────────────────
633
 
 
 
 
 
 
 
 
 
 
 
634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
 
636
  // ── Report ────────────────────────────────────────────────────────────
637
 
test_photos/mock.jpg ADDED
test_spaces_startup.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ from fastapi import FastAPI
4
+ import asyncio
5
+
6
+ app = FastAPI()
7
+
8
+ @spaces.GPU()
9
+ def test_fn():
10
+ return "Test"
11
+
12
+ with gr.Blocks() as demo:
13
+ gr.Button("Test").click(test_fn)
14
+
15
+ app_mounted = gr.mount_gradio_app(app, demo, path="/")
16
+
17
+ if hasattr(spaces, "zero") and hasattr(spaces.zero, "startup"):
18
+ print("Found 'startup' in spaces.zero!")
19
+
uploads/case_1/f82c8a9d84ed_mock.jpg ADDED