File size: 3,791 Bytes
176cf9b
56e59a7
 
4fb13be
56e59a7
2d7b7d3
01aaebd
2d7b7d3
 
2c0a1bd
56e59a7
 
 
 
 
2d7b7d3
4fb13be
 
2c0a1bd
4fb13be
 
 
 
2c0a1bd
4fb13be
2c0a1bd
4fb13be
 
 
2d7b7d3
 
 
 
 
2c0a1bd
2d7b7d3
 
 
 
 
 
56e59a7
 
2c0a1bd
3f0f6fc
176cf9b
 
2d7b7d3
2c0a1bd
2d7b7d3
176cf9b
 
2d7b7d3
56e59a7
 
 
 
 
176cf9b
 
 
 
2d7b7d3
 
 
 
176cf9b
 
01aaebd
56e59a7
01aaebd
 
56e59a7
 
 
3f0f6fc
176cf9b
56e59a7
176cf9b
2d7b7d3
3f0f6fc
2d7b7d3
3f0f6fc
316f370
 
 
3f0f6fc
 
 
 
 
 
 
 
01aaebd
176cf9b
316f370
 
 
3f0f6fc
 
316f370
 
 
3f0f6fc
2c0a1bd
5ec38d4
316f370
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
import os
import sys
import subprocess
import re

# =============================================================
# 1. Bootstrap prebuilt llama-cpp-python
# =============================================================
def bootstrap_llama_cpp():
    print("Bootstrapping llama-cpp-python...")
    from huggingface_hub import HfApi, hf_hub_download

    api = HfApi()
    files = api.list_repo_files("AIencoder/llama-cpp-wheels", repo_type="dataset")
    py_tag = f"cp{sys.version_info.major}{sys.version_info.minor}"

    candidates = []
    for p in files:
        if not p.endswith(".whl") or "linux/x86_64/cpu/" not in p or "cuda" in p.lower():
            continue
        if py_tag not in p and "py3-none" not in p:
            continue
        m = re.search(r"/0\.3\.(\d+)/", p)
        if not m or int(m.group(1)) < 20:
            continue
        candidates.append((int(m.group(1)), p))

    candidates.sort(key=lambda x: x[0], reverse=True)
    chosen = candidates[0][1]
    print(f"Selected wheel: {chosen}")
    whl_path = hf_hub_download("AIencoder/llama-cpp-wheels", chosen, repo_type="dataset")
    subprocess.check_call([
        sys.executable, "-m", "pip", "install", "--force-reinstall", whl_path
    ])
    print("llama-cpp-python ready!")

try:
    from llama_cpp import Llama
    print("llama-cpp-python already available.")
except (ImportError, RuntimeError, OSError):
    bootstrap_llama_cpp()
    from llama_cpp import Llama

import spaces
from typing import List
import gradio as gr

# =============================================================
# 2. Load GGUF Model
# =============================================================
MODEL_PATH = "Qwen3.5-0.8B.Q4_K_M.gguf"

print(f"Loading {MODEL_PATH} via llama-cpp-python ...")
llm = Llama(
    model_path=MODEL_PATH,
    n_ctx=4096,
    n_threads=2,
    verbose=False
)
print("Model loaded successfully!")

SYSTEM_PROMPT = (
    "You are Sherpa, an AI driving assistant for the CommitCon ride-hailing "
    "repositioning platform in Bengaluru. Provide concise, direct, helpful "
    "recommendations to drivers about where to reposition for high demand, "
    "earnings, and low traffic delays."
)

def run_inference(prompt: str, history: List[dict] = None) -> str:
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    if history:
        for m in history:
            messages.append({"role": m["role"], "content": m["content"]})
    messages.append({"role": "user", "content": prompt})
    response = llm.create_chat_completion(
        messages=messages, temperature=0.7, max_tokens=256
    )
    return response["choices"][0]["message"]["content"]

# =============================================================
# 3. Gradio Interface (duration=15 ensures ZeroGPU quota is preserved)
# =============================================================
@spaces.GPU(duration=15)
def gradio_chat(user_message, history):
    hist_formatted = []
    if history:
        for item in history:
            if isinstance(item, (list, tuple)) and len(item) == 2:
                u, b = item
                hist_formatted.append({"role": "user", "content": str(u)})
                if b:
                    hist_formatted.append({"role": "assistant", "content": str(b)})
            elif isinstance(item, dict):
                hist_formatted.append(item)
    return run_inference(user_message, hist_formatted)

demo = gr.ChatInterface(
    fn=gradio_chat,
    title="🧭 CommitCon Sherpa Driver Copilot",
    description="Fine-tuned Qwen 0.8B Q4_K_M — llama-cpp-python inference",
    api_name="chat"
)

# =============================================================
# 4. Native ZeroGPU Launch
# =============================================================
if __name__ == "__main__":
    demo.launch()