Jasmine Wong commited on
Commit
d770d89
·
1 Parent(s): ea47862

embed cloudflare app in iframe

Browse files
Files changed (1) hide show
  1. app.py +20 -237
app.py CHANGED
@@ -1,254 +1,37 @@
1
- import os
2
- import uuid
3
- import time
4
- from fastapi import FastAPI, Request
5
  from fastapi.responses import HTMLResponse
6
- from fastapi.middleware.cors import CORSMiddleware
7
- from pydantic import BaseModel
8
- import httpx
9
 
10
  app = FastAPI()
11
 
12
- app.add_middleware(
13
- CORSMiddleware,
14
- allow_origins=["*"],
15
- allow_methods=["*"],
16
- allow_headers=["*"],
17
- )
18
-
19
- GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
20
- GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
21
- MODEL = "llama-3.3-70b-versatile"
22
-
23
- QWEN_PERSONA = (
24
- "You are Qwen, the AutoPulse Bot — an expert AI safety analyst for autonomous vehicle fleets. "
25
- "You are precise, technical, and helpful. Always start your response with: "
26
- "'Hi, I'm Qwen the AutoPulse Bot. I am now looking through your submissions on issues and I will diagnose.'"
27
- )
28
-
29
- async def call_groq(prompt: str) -> str:
30
- async with httpx.AsyncClient(timeout=60) as client:
31
- resp = await client.post(
32
- GROQ_URL,
33
- headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
34
- json={
35
- "model": MODEL,
36
- "messages": [
37
- {"role": "system", "content": QWEN_PERSONA},
38
- {"role": "user", "content": prompt}
39
- ],
40
- "max_tokens": 2000
41
- }
42
- )
43
- data = resp.json()
44
- return data["choices"][0]["message"]["content"]
45
-
46
- class Query(BaseModel):
47
- input: str
48
-
49
- class ChatMessage(BaseModel):
50
- role: str
51
- content: str
52
-
53
- class ChatRequest(BaseModel):
54
- model: str = "qwen3"
55
- messages: list[ChatMessage]
56
- tools: list = []
57
- tool_choice: dict = {}
58
-
59
- @app.post("/triage")
60
- async def triage(query: Query):
61
- result = await call_groq(
62
- f"Run a full AV incident triage:\n"
63
- f"1. Classify incident (vehicle_id, timestamp, severity P1/P2/P3)\n"
64
- f"2. Identify affected subsystems (GNSS, LiDAR, perception, planning, control)\n"
65
- f"3. Root cause analysis ranked by confidence (ISO 26262, SAE J3016, NHTSA)\n"
66
- f"4. Response plan (immediate, short-term, long-term)\n"
67
- f"5. Formal Markdown report\n"
68
- f"End with '## Qwen's Personal Recommendation'\n\n"
69
- f"Incident: {query.input}"
70
- )
71
- return {"output": result}
72
-
73
- @app.post("/branch-debug")
74
- async def branch_debug(query: Query):
75
- result = await call_groq(
76
- f"Analyze this git diff and failure description. "
77
- f"Rank root cause suspects by file path, line range, mechanism, confidence (high/medium/low). "
78
- f"End with '## Qwen's Personal Recommendation'.\n\n{query.input}"
79
- )
80
- return {"output": result}
81
-
82
- @app.post("/forensic")
83
- async def forensic(query: Query):
84
- result = await call_groq(
85
- f"Perform forensic analysis on this content. "
86
- f"Flag suspicious patterns, security vulnerabilities, or safety issues with severity. "
87
- f"End with '## Qwen's Personal Recommendation'.\n\n{query.input}"
88
- )
89
- return {"output": result}
90
-
91
- @app.post("/v1/chat/completions")
92
- async def chat_completions(req: ChatRequest):
93
- user_messages = [m.content for m in req.messages if m.role == "user"]
94
- user_input = user_messages[-1] if user_messages else ""
95
- result = await call_groq(user_input)
96
- return {
97
- "id": f"chatcmpl-{uuid.uuid4().hex}",
98
- "object": "chat.completion",
99
- "created": int(time.time()),
100
- "model": "qwen3-autopulse-bot",
101
- "choices": [{"index": 0, "message": {"role": "assistant", "content": result}, "finish_reason": "stop"}]
102
- }
103
-
104
- @app.post("/chat/completions")
105
- async def chat_completions_alias(req: ChatRequest):
106
- return await chat_completions(req)
107
-
108
- @app.get("/health")
109
- async def health():
110
- return {"status": "ok", "model": "groq", "persona": "Qwen AutoPulse Bot"}
111
-
112
  @app.get("/", response_class=HTMLResponse)
113
  async def index():
114
  return """
115
  <!DOCTYPE html>
116
- <html lang="en" class="dark">
117
  <head>
118
- <meta charset="UTF-8">
119
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
120
- <title>DriveCore — AV Safety Intelligence</title>
121
- <style>
122
- * { margin: 0; padding: 0; box-sizing: border-box; }
123
- body { font-family: 'Inter', sans-serif; background: #0a0a0f; color: #e2e8f0; min-height: 100vh; }
124
- .header { padding: 20px 40px; border-bottom: 1px solid #1e293b; display: flex; align-items: center; gap: 12px; }
125
- .logo { width: 36px; height: 36px; background: #6366f1; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; }
126
- .brand { font-size: 18px; font-weight: 700; }
127
- .badge { font-size: 10px; background: #1e293b; border: 1px solid #334155; padding: 2px 8px; border-radius: 20px; color: #94a3b8; margin-left: auto; }
128
- .container { max-width: 900px; margin: 0 auto; padding: 40px 20px; }
129
- .tabs { display: flex; gap: 8px; margin-bottom: 24px; border-bottom: 1px solid #1e293b; padding-bottom: 0; }
130
- .tab { padding: 10px 20px; border-radius: 8px 8px 0 0; cursor: pointer; font-size: 14px; font-weight: 500; color: #64748b; border: none; background: none; transition: all 0.2s; }
131
- .tab.active { color: #6366f1; border-bottom: 2px solid #6366f1; }
132
- .tab:hover { color: #e2e8f0; }
133
- .panel { display: none; }
134
- .panel.active { display: block; }
135
- textarea { width: 100%; background: #0f172a; border: 1px solid #1e293b; border-radius: 8px; padding: 16px; color: #e2e8f0; font-size: 14px; resize: vertical; font-family: inherit; }
136
- textarea:focus { outline: none; border-color: #6366f1; }
137
- .btn { background: #6366f1; color: white; border: none; padding: 12px 24px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; margin-top: 12px; transition: all 0.2s; }
138
- .btn:hover { background: #4f46e5; }
139
- .btn:disabled { opacity: 0.5; cursor: not-allowed; }
140
- .result { margin-top: 24px; background: #0f172a; border: 1px solid #1e293b; border-radius: 8px; padding: 20px; white-space: pre-wrap; font-size: 13px; line-height: 1.7; display: none; }
141
- .result.show { display: block; }
142
- .loading { color: #6366f1; font-size: 13px; margin-top: 12px; display: none; }
143
- .loading.show { display: block; }
144
- h2 { font-size: 16px; font-weight: 600; margin-bottom: 8px; }
145
- p { font-size: 13px; color: #64748b; margin-bottom: 16px; }
146
- .hero { text-align: center; padding: 60px 0 40px; }
147
- .hero h1 { font-size: 42px; font-weight: 800; line-height: 1.1; margin-bottom: 16px; }
148
- .hero h1 span { color: #6366f1; }
149
- .hero p { font-size: 16px; color: #64748b; max-width: 600px; margin: 0 auto 32px; }
150
- .powered { font-size: 11px; color: #475569; text-align: center; margin-top: 8px; }
151
- </style>
152
  </head>
153
  <body>
154
- <div class="header">
155
- <div class="logo">🚗</div>
156
- <span class="brand">DriveCore</span>
157
- <span class="badge">⚡ Powered by AMD Instinct GPU + Qwen3</span>
158
- </div>
159
- <div class="container">
160
- <div class="hero">
161
- <h1>Turn raw incident logs into<br><span>actionable safety intelligence</span>.</h1>
162
- <p>DriveCore routes every AV event through a multi-agent AI pipeline — surfacing root causes, compliance concerns, and coaching plans in seconds.</p>
163
- </div>
164
-
165
- <div class="tabs">
166
- <button class="tab active" onclick="showTab('triage')">🚨 Incident Triage</button>
167
- <button class="tab" onclick="showTab('branch')">🔀 Branch Debug</button>
168
- <button class="tab" onclick="showTab('forensic')">🔬 Forensic Analysis</button>
169
- </div>
170
-
171
- <div id="triage" class="panel active">
172
- <h2>Incident Triage</h2>
173
- <p>Submit an AV incident description. Qwen Bot will run a 5-step agent pipeline and produce a formal safety report.</p>
174
- <textarea id="triage-input" rows="6" placeholder="e.g. Vehicle AV-042 lost GNSS signal at 14:23 on Highway 101 and stopped unexpectedly..."></textarea>
175
- <button class="btn" onclick="runTriage()">Run Triage Pipeline</button>
176
- <div class="loading" id="triage-loading">🤖 Qwen Bot is analyzing your incident through 5 agent steps...</div>
177
- <div class="result" id="triage-result"></div>
178
- </div>
179
-
180
- <div id="branch" class="panel">
181
- <h2>Branch Debug</h2>
182
- <p>Paste a git diff and describe the failure. Qwen Bot will rank root cause suspects by file, line, and confidence.</p>
183
- <textarea id="branch-input" rows="6" placeholder="Git diff:\n--- a/src/gnss.py\n+++ b/src/gnss.py\n...\n\nFailure: Vehicle stopped unexpectedly after merge"></textarea>
184
- <button class="btn" onclick="runBranch()">Analyze Branch</button>
185
- <div class="loading" id="branch-loading">🤖 Qwen Bot is analyzing your diff...</div>
186
- <div class="result" id="branch-result"></div>
187
- </div>
188
-
189
- <div id="forensic" class="panel">
190
- <h2>Forensic Analysis</h2>
191
- <p>Submit code, logs, or URLs for forensic analysis. Qwen Bot will flag suspicious patterns and safety issues.</p>
192
- <textarea id="forensic-input" rows="6" placeholder="Paste code, logs, or URL to analyze..."></textarea>
193
- <button class="btn" onclick="runForensic()">Run Forensic Analysis</button>
194
- <div class="loading" id="forensic-loading">🤖 Qwen Bot is running forensic analysis...</div>
195
- <div class="result" id="forensic-result"></div>
196
- </div>
197
-
198
- <p class="powered">Powered by AMD Instinct GPU ⚡ | Qwen3 via LangChain | Built for AMD Developer Cloud Hackathon</p>
199
- </div>
200
-
201
- <script>
202
- function showTab(name) {
203
- document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
204
- document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
205
- document.getElementById(name).classList.add('active');
206
- event.target.classList.add('active');
207
- }
208
-
209
- async function callAPI(endpoint, input, resultId, loadingId) {
210
- const result = document.getElementById(resultId);
211
- const loading = document.getElementById(loadingId);
212
- result.classList.remove('show');
213
- loading.classList.add('show');
214
- try {
215
- const resp = await fetch(endpoint, {
216
- method: 'POST',
217
- headers: {'Content-Type': 'application/json'},
218
- body: JSON.stringify({input})
219
- });
220
- const data = await resp.json();
221
- result.textContent = data.output || JSON.stringify(data, null, 2);
222
- result.classList.add('show');
223
- } catch(e) {
224
- result.textContent = 'Error: ' + e.message;
225
- result.classList.add('show');
226
- }
227
- loading.classList.remove('show');
228
- }
229
-
230
- function runTriage() {
231
- const input = document.getElementById('triage-input').value;
232
- if (!input) return;
233
- callAPI('/triage', input, 'triage-result', 'triage-loading');
234
- }
235
-
236
- function runBranch() {
237
- const input = document.getElementById('branch-input').value;
238
- if (!input) return;
239
- callAPI('/branch-debug', input, 'branch-result', 'branch-loading');
240
- }
241
-
242
- function runForensic() {
243
- const input = document.getElementById('forensic-input').value;
244
- if (!input) return;
245
- callAPI('/forensic', input, 'forensic-result', 'forensic-loading');
246
- }
247
- </script>
248
  </body>
249
  </html>
250
  """
251
 
252
  if __name__ == "__main__":
253
- import uvicorn
254
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI
 
 
 
2
  from fastapi.responses import HTMLResponse
3
+ import uvicorn
 
 
4
 
5
  app = FastAPI()
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  @app.get("/", response_class=HTMLResponse)
8
  async def index():
9
  return """
10
  <!DOCTYPE html>
11
+ <html>
12
  <head>
13
+ <meta charset="UTF-8">
14
+ <title>DriveCore — AV Safety Intelligence</title>
15
+ <style>
16
+ * { margin: 0; padding: 0; box-sizing: border-box; }
17
+ body { background: #07080f; font-family: sans-serif; height: 100vh; display: flex; flex-direction: column; }
18
+ .bar { padding: 10px 20px; background: #0d0f1a; border-bottom: 1px solid #1e2235; display: flex; align-items: center; gap: 10px; }
19
+ .logo { background: #6366f1; width: 28px; height: 28px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 14px; }
20
+ .brand { color: #e2e8f0; font-weight: 700; font-size: 15px; }
21
+ .badge { margin-left: auto; font-size: 10px; background: #131627; border: 1px solid #1e2235; padding: 3px 10px; border-radius: 20px; color: #64748b; }
22
+ iframe { flex: 1; border: none; width: 100%; height: calc(100vh - 50px); }
23
+ </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  </head>
25
  <body>
26
+ <div class="bar">
27
+ <div class="logo">🚗</div>
28
+ <span class="brand">DriveCore</span>
29
+ <span class="badge">⚡ AMD Instinct GPU + Qwen3 + LangChain</span>
30
+ </div>
31
+ <iframe src="https://drivecore.dr-coke.workers.dev/" allowfullscreen></iframe>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  </body>
33
  </html>
34
  """
35
 
36
  if __name__ == "__main__":
 
37
  uvicorn.run(app, host="0.0.0.0", port=7860)