ndahlbom commited on
Commit
66a1e77
·
verified ·
1 Parent(s): 4f1f685

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -84
app.py CHANGED
@@ -2,118 +2,101 @@ import gradio as gr
2
  import subprocess
3
  from huggingface_hub import hf_hub_download
4
 
5
- # 1. Install llama-cpp-python in runtime
6
  subprocess.run("pip install -q 'llama_cpp_python==0.3.15'", shell=True, check=False)
7
-
8
  from llama_cpp import Llama
9
 
10
- # 2. Load GGUF model from Hugging Face
11
  MODEL_REPO = "Jeppcode/ScalableLab2"
12
  GGUF_FILENAME = "model-q4_k_m.gguf"
13
 
14
  print(f"Downloading GGUF model {MODEL_REPO}/{GGUF_FILENAME} ...")
15
- model_path = hf_hub_download(
16
- repo_id=MODEL_REPO,
17
- filename=GGUF_FILENAME,
18
- )
 
 
 
 
19
 
20
- print("Initializing llama.cpp LLM ...")
21
- llm = Llama(
22
- model_path=model_path,
23
- n_ctx=2048,
24
- n_threads=2,
25
- n_batch=64,
26
- use_mmap=True,
27
- use_mlock=False,
28
- )
 
 
29
 
30
- # Hardcoded system prompt (since style selector is removed)
31
- SYSTEM_PROMPT = "You are a helpful teaching assistant. Give clear, structured and detailed explanations."
 
 
 
 
 
 
32
 
33
- def _extract_text_from_content(content):
34
- """
35
- Extracts text from Gradio 6 message format.
36
- """
37
  if isinstance(content, list):
38
- texts = []
39
- for block in content:
40
- if isinstance(block, dict) and block.get("type") == "text":
41
- texts.append(block.get("text", ""))
42
- else:
43
- texts.append(str(block))
44
- return "\n".join(t for t in texts if t)
45
- else:
46
- return str(content)
47
 
48
- def build_prompt(message, history):
49
- """
50
- Builds the prompt using the hardcoded system prompt.
51
- """
52
- prompt_parts = []
53
- prompt_parts.append(f"System: {SYSTEM_PROMPT}\n")
54
- prompt_parts.append("Conversation:\n")
55
 
 
56
  for msg in history or []:
57
  role = msg.get("role")
58
- content = _extract_text_from_content(msg.get("content", ""))
59
- if not content:
60
- continue
61
- if role == "user":
62
- prompt_parts.append(f"User: {content}\n")
63
- elif role == "assistant":
64
- prompt_parts.append(f"Assistant: {content}\n")
65
- elif role == "system":
66
- prompt_parts.append(f"System (previous): {content}\n")
67
 
68
- # Current user message
69
- prompt_parts.append(f"User: {message}\n")
70
- prompt_parts.append("Assistant:")
71
- full_prompt = "".join(prompt_parts)
72
- return full_prompt
73
-
74
- def chat_fn(message, history, max_new_tokens):
75
- """
76
- Main chat function.
77
- Only accepts max_new_tokens as an additional input now.
78
- """
79
- prompt = build_prompt(message, history)
80
-
81
- # Internal defaults for the removed sliders
82
- temperature = 0.7
83
- top_p = 0.9
84
- repetition_penalty = 1.0
85
 
 
86
  output = llm(
87
  prompt,
88
  max_tokens=int(max_new_tokens),
89
- temperature=temperature,
90
- top_p=top_p,
91
- repeat_penalty=repetition_penalty,
92
- stop=["User:", "Assistant:", "System:", "Conversation:"],
93
  )
94
- reply = output["choices"][0]["text"].strip()
95
- return reply
 
96
 
97
- # 4. Only keep the Max Token slider
98
  max_new_tokens_slider = gr.Slider(
99
- minimum=16,
100
- maximum=256,
101
- value=64,
102
- step=8,
103
- label="Max new tokens (response length)",
 
 
 
 
 
 
 
104
  )
105
 
 
106
  demo = gr.ChatInterface(
107
  fn=chat_fn,
108
  title="Lab 2 – Fine-tuned GGUF model",
109
- description=(
110
- "Chat with our fine-tuned Llama-based model, converted to GGUF and "
111
- "loaded via llama.cpp from Jeppcode/ScalableLab2."
112
- ),
113
- additional_inputs=[
114
- max_new_tokens_slider,
115
- ],
116
- additional_inputs_accordion="Generation controls",
117
  )
118
 
119
  if __name__ == "__main__":
 
2
  import subprocess
3
  from huggingface_hub import hf_hub_download
4
 
5
+ # --- 1. Setup & Install ---
6
  subprocess.run("pip install -q 'llama_cpp_python==0.3.15'", shell=True, check=False)
 
7
  from llama_cpp import Llama
8
 
9
+ # --- 2. Load Model (GGUF) ---
10
  MODEL_REPO = "Jeppcode/ScalableLab2"
11
  GGUF_FILENAME = "model-q4_k_m.gguf"
12
 
13
  print(f"Downloading GGUF model {MODEL_REPO}/{GGUF_FILENAME} ...")
14
+ try:
15
+ model_path = hf_hub_download(
16
+ repo_id=MODEL_REPO,
17
+ filename=GGUF_FILENAME,
18
+ )
19
+ except Exception as e:
20
+ print(f"Error downloading model: {e}")
21
+ model_path = ""
22
 
23
+ llm = None
24
+ if model_path:
25
+ print("Initializing llama.cpp LLM ...")
26
+ llm = Llama(
27
+ model_path=model_path,
28
+ n_ctx=2048,
29
+ n_threads=2,
30
+ n_batch=64,
31
+ use_mmap=True,
32
+ use_mlock=False,
33
+ )
34
 
35
+ # --- 3. Style / System Prompts ---
36
+ # These are the "Buttons" logic to change how the AI behaves
37
+ STYLE_SYSTEM_PROMPTS = {
38
+ "Default": "You are a helpful, polite assistant.",
39
+ "Short answer": "Answer as concisely as possible, usually in 1–3 sentences.",
40
+ "Detailed explanation": "Give clear, structured and detailed explanations.",
41
+ "Step-by-step reasoning": "Think step by step and explain your reasoning clearly.",
42
+ }
43
 
44
+ def _extract_text(content):
 
 
 
45
  if isinstance(content, list):
46
+ return "\n".join(b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text")
47
+ return str(content)
 
 
 
 
 
 
 
48
 
49
+ def chat_fn(message, history, max_new_tokens, style):
50
+ if not llm: return "Error: Model not loaded."
51
+
52
+ # Select the specific system prompt based on the button chosen
53
+ system_prompt = STYLE_SYSTEM_PROMPTS.get(style, STYLE_SYSTEM_PROMPTS["Default"])
 
 
54
 
55
+ prompt = f"System: {system_prompt}\nConversation:\n"
56
  for msg in history or []:
57
  role = msg.get("role")
58
+ txt = _extract_text(msg.get("content", ""))
59
+ if txt:
60
+ if role == "user": prompt += f"User: {txt}\n"
61
+ elif role == "assistant": prompt += f"Assistant: {txt}\n"
 
 
 
 
 
62
 
63
+ prompt += f"User: {message}\nAssistant:"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ # Default internal values for randomness
66
  output = llm(
67
  prompt,
68
  max_tokens=int(max_new_tokens),
69
+ temperature=0.7,
70
+ top_p=0.9,
71
+ stop=["User:", "Assistant:", "System:"],
 
72
  )
73
+ return output["choices"][0]["text"].strip()
74
+
75
+ # --- 4. UI Controls ---
76
 
77
+ # Slider for length
78
  max_new_tokens_slider = gr.Slider(
79
+ minimum=16,
80
+ maximum=256,
81
+ value=64,
82
+ step=8,
83
+ label="Max Response Length"
84
+ )
85
+
86
+ # The "Buttons" at the bottom for Style
87
+ style_radio = gr.Radio(
88
+ choices=["Default", "Short answer", "Detailed explanation", "Step-by-step reasoning"],
89
+ value="Detailed explanation",
90
+ label="Answer Style"
91
  )
92
 
93
+ # --- 5. Launch App (Clean / No Theme) ---
94
  demo = gr.ChatInterface(
95
  fn=chat_fn,
96
  title="Lab 2 – Fine-tuned GGUF model",
97
+ description="Chat with the fine-tuned Llama model. Use the controls below to change the response style.",
98
+ additional_inputs=[max_new_tokens_slider, style_radio],
99
+ additional_inputs_accordion="Controls",
 
 
 
 
 
100
  )
101
 
102
  if __name__ == "__main__":