Maxwell commited on
Commit
930ac2c
·
verified ·
1 Parent(s): f509730

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -464
app.py DELETED
@@ -1,464 +0,0 @@
1
- import os
2
- import json
3
- import time
4
- import uuid
5
- import asyncio
6
- import threading
7
- import queue as queue_mod
8
- import gradio as gr
9
- from fastapi import FastAPI, Request
10
- from fastapi.responses import StreamingResponse, JSONResponse
11
- from huggingface_hub import hf_hub_download
12
- from llama_cpp import Llama
13
-
14
- HF_TOKEN = os.environ.get("HF_TOKEN")
15
- BASE_PATH = "/tmp/base.gguf"
16
- LORA_PATH = "/tmp/lumen-adapter.gguf"
17
- MEMORY_FILE = "/tmp/memories.json"
18
-
19
- SYSTEM_PROMPT = (
20
- "You are a helpful AI named Lumen 1.2.5 by Axion Labs."
21
- )
22
-
23
- llm = None
24
- infer_lock = threading.Lock()
25
-
26
-
27
- # ── Memory ────────────────────────────────────────────────────────────────────
28
-
29
- def _load_memories():
30
- try:
31
- if not os.path.exists(MEMORY_FILE):
32
- return []
33
- with open(MEMORY_FILE) as f:
34
- return json.load(f)
35
- except Exception:
36
- return []
37
-
38
-
39
- def _save_memories(memories):
40
- try:
41
- with open(MEMORY_FILE, "w") as f:
42
- json.dump(memories, f, indent=2)
43
- except Exception:
44
- pass
45
-
46
-
47
- def get_memories():
48
- return _load_memories()
49
-
50
-
51
- def add_memory(text):
52
- memories = _load_memories()
53
- memories.append({"text": text.strip(), "addedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
54
- _save_memories(memories)
55
- return memories
56
-
57
-
58
- def remove_all_memories():
59
- _save_memories([])
60
-
61
-
62
- def remove_memory_by_index(index):
63
- memories = _load_memories()
64
- if 0 <= index < len(memories):
65
- memories.pop(index)
66
- _save_memories(memories)
67
- return True
68
- return False
69
-
70
-
71
- def build_system_prompt():
72
- memories = get_memories()
73
- prompt = SYSTEM_PROMPT
74
- if memories:
75
- notes = "\n".join(f"- {m['text']}" for m in memories)
76
- prompt += f"\n\nPersistent notes (always keep in mind):\n{notes}"
77
- return prompt
78
-
79
-
80
- def memories_display_text():
81
- memories = get_memories()
82
- if not memories:
83
- return "No memories saved."
84
- return "\n".join(f"{i + 1}. {m['text']}" for i, m in enumerate(memories))
85
-
86
-
87
- # ── Model loading ─────────────────────────────────────────────────────────────
88
-
89
- def _load_model():
90
- global llm
91
- if not os.path.exists(BASE_PATH):
92
- print("Downloading base model…")
93
- hf_hub_download(
94
- repo_id="bartowski/Meta-Llama-3.1-8B-Instruct-GGUF",
95
- filename="Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf",
96
- local_dir="/tmp",
97
- )
98
- os.rename("/tmp/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf", BASE_PATH)
99
-
100
- if not os.path.exists(LORA_PATH):
101
- print("Downloading adapter…")
102
- hf_hub_download(
103
- repo_id="RavikxxBGamin/Lumen",
104
- filename="lumen-dpo.gguf",
105
- token=HF_TOKEN,
106
- local_dir="/tmp",
107
- )
108
-
109
- print("Loading model…")
110
- llm = Llama(
111
- model_path=BASE_PATH,
112
- lora_path=LORA_PATH,
113
- n_ctx=8192,
114
- n_threads=2,
115
- verbose=False,
116
- )
117
- print("Model ready.")
118
-
119
-
120
- # ── FastAPI ───────────────────────────────────────────────────────────────────
121
-
122
- fastapi_app = FastAPI()
123
-
124
-
125
- @fastapi_app.on_event("startup")
126
- async def startup():
127
- loop = asyncio.get_event_loop()
128
- loop.run_in_executor(None, _load_model)
129
-
130
-
131
- @fastapi_app.get("/health")
132
- def health():
133
- return {"status": "ready" if llm is not None else "loading"}
134
-
135
-
136
- @fastapi_app.get("/v1/memories")
137
- def api_list_memories():
138
- return {"memories": get_memories()}
139
-
140
-
141
- @fastapi_app.post("/v1/memories")
142
- async def api_add_memory(request: Request):
143
- body = await request.json()
144
- text = (body.get("text") or "").strip()
145
- if not text:
146
- return JSONResponse({"error": "text is required"}, status_code=400)
147
- updated = add_memory(text)
148
- return {"memories": updated}
149
-
150
-
151
- @fastapi_app.delete("/v1/memories/{index}")
152
- def api_delete_memory(index: int):
153
- if remove_memory_by_index(index):
154
- return {"memories": get_memories()}
155
- return JSONResponse({"error": "index out of range"}, status_code=404)
156
-
157
-
158
- @fastapi_app.post("/v1/chat/completions")
159
- async def chat_completions(request: Request):
160
- if llm is None:
161
- return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
162
-
163
- body = await request.json()
164
- messages = body.get("messages", [])
165
- max_tokens = int(body.get("max_tokens", 512))
166
- temperature = float(body.get("temperature", 0.7))
167
- stream = body.get("stream", False)
168
- model_id = body.get("model", "lumen")
169
- use_memories = body.get("use_memories", False)
170
-
171
- sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
172
- if not any(m.get("role") == "system" for m in messages):
173
- messages = [{"role": "system", "content": sys_prompt}] + messages
174
-
175
- if stream:
176
- async def event_stream():
177
- resp_id = "chatcmpl-" + uuid.uuid4().hex
178
- created = int(time.time())
179
- q = queue_mod.Queue(maxsize=64)
180
- DONE = object()
181
-
182
- def produce():
183
- try:
184
- with infer_lock:
185
- for chunk in llm.create_chat_completion(
186
- messages=messages,
187
- max_tokens=max_tokens,
188
- temperature=temperature,
189
- stream=True,
190
- ):
191
- q.put(chunk)
192
- except Exception as e:
193
- q.put(e)
194
- finally:
195
- q.put(DONE)
196
-
197
- threading.Thread(target=produce, daemon=True).start()
198
- while True:
199
- chunk = await asyncio.to_thread(q.get)
200
- if chunk is DONE:
201
- break
202
- if isinstance(chunk, Exception):
203
- yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
204
- break
205
- delta = chunk["choices"][0]["delta"]
206
- finish = chunk["choices"][0].get("finish_reason")
207
- data = {
208
- "id": resp_id,
209
- "object": "chat.completion.chunk",
210
- "created": created,
211
- "model": model_id,
212
- "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
213
- }
214
- yield f"data: {json.dumps(data)}\n\n"
215
- yield "data: [DONE]\n\n"
216
-
217
- return StreamingResponse(event_stream(), media_type="text/event-stream")
218
-
219
- def generate():
220
- with infer_lock:
221
- return llm.create_chat_completion(
222
- messages=messages,
223
- max_tokens=max_tokens,
224
- temperature=temperature,
225
- stream=False,
226
- )
227
-
228
- result = await asyncio.to_thread(generate)
229
- return JSONResponse(result)
230
-
231
-
232
- # ── Gradio chat helpers ───────────────────────────────────────────────────────
233
-
234
- def user_submit(message, history):
235
- if not message.strip():
236
- return "", history
237
- return "", history + [{"role": "user", "content": message}]
238
-
239
-
240
- def bot_respond(history, temperature, max_tokens):
241
- if llm is None:
242
- yield history + [{"role": "assistant", "content": "Model is still loading — please wait a moment and try again."}]
243
- return
244
-
245
- messages = [{"role": "system", "content": build_system_prompt()}]
246
- for item in history:
247
- if not isinstance(item, dict):
248
- continue
249
- content = item.get("content", "")
250
- if isinstance(content, list):
251
- content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
252
- messages.append({"role": item["role"], "content": content})
253
-
254
- response = ""
255
- working_history = history + [{"role": "assistant", "content": ""}]
256
- with infer_lock:
257
- for chunk in llm.create_chat_completion(
258
- messages=messages,
259
- max_tokens=int(max_tokens),
260
- temperature=float(temperature),
261
- stream=True,
262
- ):
263
- delta = chunk["choices"][0]["delta"].get("content", "")
264
- response += delta
265
- working_history[-1]["content"] = response
266
- yield working_history
267
-
268
-
269
- def model_status():
270
- if llm is not None:
271
- return "<p class='status ready'>● Model ready</p>"
272
- return "<p class='status loading'>● Loading model… (first boot takes a few minutes)</p>"
273
-
274
-
275
- def do_add_memory(text):
276
- if not text.strip():
277
- return "", memories_display_text()
278
- add_memory(text.strip())
279
- return "", memories_display_text()
280
-
281
-
282
- def do_clear_memories():
283
- remove_all_memories()
284
- return memories_display_text()
285
-
286
-
287
- # ── Theme & CSS ───────────────────────────────────────────────────────────────
288
-
289
- THEME = gr.themes.Base(
290
- primary_hue=gr.themes.colors.orange,
291
- secondary_hue=gr.themes.colors.stone,
292
- neutral_hue=gr.themes.colors.stone,
293
- font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
294
- font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
295
- ).set(
296
- body_background_fill="#110d08",
297
- body_background_fill_dark="#110d08",
298
- block_background_fill="#1c1510",
299
- block_background_fill_dark="#1c1510",
300
- block_border_color="#2e2218",
301
- block_border_color_dark="#2e2218",
302
- block_label_background_fill="#1c1510",
303
- block_label_background_fill_dark="#1c1510",
304
- input_background_fill="#150f0a",
305
- input_background_fill_dark="#150f0a",
306
- input_border_color="#2e2218",
307
- input_border_color_dark="#2e2218",
308
- button_primary_background_fill="#cc785c",
309
- button_primary_background_fill_hover="#b8664a",
310
- button_primary_background_fill_dark="#cc785c",
311
- button_primary_text_color="#fff",
312
- button_secondary_background_fill="#2e2218",
313
- button_secondary_background_fill_hover="#3a2c1e",
314
- button_secondary_background_fill_dark="#2e2218",
315
- button_secondary_text_color="#d4b896",
316
- body_text_color="#e8ddd0",
317
- body_text_color_dark="#e8ddd0",
318
- block_label_text_color="#a08060",
319
- block_label_text_color_dark="#a08060",
320
- )
321
-
322
- CSS = """
323
- /* ── Layout ── */
324
- .gradio-container { max-width: 820px !important; margin: 0 auto !important; padding: 0 12px !important; }
325
- footer { display: none !important; }
326
-
327
- /* ── Header ── */
328
- #lumen-header { padding: 24px 0 8px; border-bottom: 1px solid #2e2218; margin-bottom: 16px; }
329
- #lumen-header h1 { font-size: 1.6em; font-weight: 700; margin: 0 0 2px; color: #e8ddd0; letter-spacing: -0.01em; }
330
- #lumen-header h1 span { color: #cc785c; }
331
- #lumen-header p { color: #7a6050; margin: 0; font-size: 0.85em; }
332
-
333
- /* ── Status ── */
334
- .status { margin: 0 0 10px; font-size: 0.8em; font-weight: 500; }
335
- .status.ready { color: #6aa87a; }
336
- .status.loading { color: #c9994a; }
337
-
338
- /* ── Chatbot ── */
339
- .chatbot-wrap .message.user { background: #2a1e14 !important; border: 1px solid #3a2c1e !important; }
340
- .chatbot-wrap .message.bot { background: #1c1510 !important; border: 1px solid #2e2218 !important; }
341
- .chatbot-wrap .message { border-radius: 8px !important; }
342
-
343
- /* ── Input row ── */
344
- .input-row textarea {
345
- background: #150f0a !important;
346
- border: 1px solid #3a2c1e !important;
347
- border-radius: 8px !important;
348
- color: #e8ddd0 !important;
349
- resize: none !important;
350
- }
351
- .input-row textarea:focus { border-color: #cc785c !important; outline: none !important; }
352
- .send-btn {
353
- background: #cc785c !important;
354
- border: none !important;
355
- border-radius: 8px !important;
356
- color: #fff !important;
357
- font-size: 1.1em !important;
358
- min-width: 48px !important;
359
- }
360
- .send-btn:hover { background: #b8664a !important; }
361
-
362
- /* ── Sliders ── */
363
- .settings-row { margin: 10px 0 4px; gap: 16px; }
364
- .settings-row label { color: #a08060 !important; font-size: 0.8em !important; }
365
-
366
- /* ── Memory panel ── */
367
- .memory-panel { margin-top: 8px; border-top: 1px solid #2e2218; padding-top: 10px; }
368
- .memory-panel .gr-accordion-header { color: #a08060 !important; font-size: 0.82em !important; }
369
- .memory-list textarea {
370
- font-size: 0.82em !important;
371
- color: #a08060 !important;
372
- background: #110d08 !important;
373
- border: 1px solid #2e2218 !important;
374
- border-radius: 6px !important;
375
- }
376
-
377
- /* ── Footer ── */
378
- #lumen-footer { color: #4a3828; font-size: 0.75em; text-align: center; padding: 14px 0; border-top: 1px solid #2e2218; margin-top: 12px; }
379
- #lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }
380
- """
381
-
382
- # ── Gradio UI ─────────────────────────────────────────────────────────────────
383
-
384
- with gr.Blocks(theme=THEME, css=CSS, title="Lumen — Axion Labs") as demo:
385
-
386
- gr.HTML("""
387
- <div id="lumen-header">
388
- <h1>⚛ <span>Lumen</span></h1>
389
- <p>Fine-tuned Llama 3.1 8B · by Axion Labs · free, no key needed</p>
390
- </div>
391
- """)
392
-
393
- status_html = gr.HTML(model_status)
394
-
395
- chatbot = gr.Chatbot(
396
- type="messages",
397
- height=440,
398
- show_copy_button=True,
399
- elem_classes=["chatbot-wrap"],
400
- label="",
401
- show_label=False,
402
- bubble_full_width=False,
403
- )
404
-
405
- with gr.Row(elem_classes=["input-row"]):
406
- msg_box = gr.Textbox(
407
- placeholder="Message Lumen…",
408
- show_label=False,
409
- scale=5,
410
- container=False,
411
- autofocus=True,
412
- lines=1,
413
- max_lines=6,
414
- )
415
- send_btn = gr.Button("↑", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)
416
-
417
- with gr.Row(elem_classes=["settings-row"]):
418
- temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
419
- max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens", scale=1)
420
-
421
- with gr.Accordion("Memory", open=False, elem_classes=["memory-panel"]):
422
- mem_display = gr.Textbox(
423
- value=memories_display_text,
424
- label="",
425
- lines=4,
426
- interactive=False,
427
- show_copy_button=False,
428
- elem_classes=["memory-list"],
429
- every=10,
430
- )
431
- with gr.Row():
432
- mem_input = gr.Textbox(placeholder="Add a memory…", show_label=False, scale=3, container=False)
433
- mem_add_btn = gr.Button("Save", scale=1, size="sm")
434
- mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")
435
-
436
- gr.HTML("""
437
- <div id="lumen-footer">
438
- OpenAI-compatible API: <code>POST /v1/chat/completions</code>
439
- &nbsp;·&nbsp; use with Axion CLI via <code>/model lumen</code>
440
- </div>
441
- """)
442
-
443
- # ── Event wiring ──────────────────────────────────────────────────────────
444
-
445
- # Submit on Enter or button click: append user message, then stream response
446
- msg_box.submit(
447
- user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
448
- ).then(
449
- bot_respond, [chatbot, temperature, max_tokens], chatbot
450
- )
451
- send_btn.click(
452
- user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
453
- ).then(
454
- bot_respond, [chatbot, temperature, max_tokens], chatbot
455
- )
456
-
457
- mem_add_btn.click(do_add_memory, [mem_input], [mem_input, mem_display])
458
- mem_input.submit(do_add_memory, [mem_input], [mem_input, mem_display])
459
- mem_clr_btn.click(do_clear_memories, [], [mem_display])
460
-
461
- demo.load(model_status, outputs=status_html)
462
-
463
-
464
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")