ndahlbom commited on
Commit
3f78751
·
verified ·
1 Parent(s): fb839a0

Rename nikapp.py to app.py

Browse files
Files changed (2) hide show
  1. app.py +203 -0
  2. nikapp.py +0 -166
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
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
+ # 3. System Prompts
31
+ STYLE_SYSTEM_PROMPTS = {
32
+ "Default": "You are a helpful, polite assistant.",
33
+ "Short answer": (
34
+ "You are a helpful assistant. Answer as concisely as possible, usually in 1–3 sentences."
35
+ ),
36
+ "Detailed explanation": (
37
+ "You are a helpful teaching assistant. Give clear, structured and detailed explanations, "
38
+ "often with bullet points or numbered steps when useful."
39
+ ),
40
+ "Step-by-step reasoning": (
41
+ "You are a careful problem solver. Think step by step and explain your reasoning clearly "
42
+ "before giving the final answer."
43
+ ),
44
+ }
45
+
46
+ def _extract_text_from_content(content):
47
+ if isinstance(content, list):
48
+ texts = []
49
+ for block in content:
50
+ if isinstance(block, dict) and block.get("type") == "text":
51
+ texts.append(block.get("text", ""))
52
+ else:
53
+ texts.append(str(block))
54
+ return "\n".join(t for t in texts if t)
55
+ else:
56
+ return str(content)
57
+
58
+ def build_prompt(message, history, style):
59
+ system_prompt = STYLE_SYSTEM_PROMPTS.get(style, STYLE_SYSTEM_PROMPTS["Default"])
60
+ prompt_parts = []
61
+ prompt_parts.append(f"System: {system_prompt}\n")
62
+ prompt_parts.append("Conversation:\n")
63
+
64
+ for msg in history or []:
65
+ role = msg.get("role")
66
+ content = _extract_text_from_content(msg.get("content", ""))
67
+ if not content:
68
+ continue
69
+ if role == "user":
70
+ prompt_parts.append(f"User: {content}\n")
71
+ elif role == "assistant":
72
+ prompt_parts.append(f"Assistant: {content}\n")
73
+ elif role == "system":
74
+ prompt_parts.append(f"System (previous): {content}\n")
75
+
76
+ prompt_parts.append(f"User: {message}\n")
77
+ prompt_parts.append("Assistant:")
78
+ return "".join(prompt_parts)
79
+
80
+ def chat_fn(message, history, max_new_tokens, style):
81
+ # Removed sliders are now hardcoded defaults here
82
+ temperature = 0.7
83
+ top_p = 0.9
84
+ repetition_penalty = 1.1
85
+
86
+ prompt = build_prompt(message, history, style)
87
+
88
+ # Simple logic for temperature
89
+ if temperature <= 0.0:
90
+ temperature = 0.0
91
+ top_p = 1.0
92
+
93
+ output = llm(
94
+ prompt,
95
+ max_tokens=int(max_new_tokens),
96
+ temperature=temperature,
97
+ top_p=top_p,
98
+ repeat_penalty=repetition_penalty,
99
+ stop=["User:", "Assistant:", "System:", "Conversation:"],
100
+ )
101
+ reply = output["choices"][0]["text"].strip()
102
+ return reply
103
+
104
+ # --- Christmas Theme Configuration ---
105
+
106
+ # 1. THEME: Red (Santa) and Green (Tree)
107
+ christmas_theme = gr.themes.Soft(
108
+ primary_hue="red",
109
+ secondary_hue="green",
110
+ neutral_hue="slate",
111
+ ).set(
112
+ body_background_fill="transparent",
113
+ block_background_fill="rgba(255, 250, 240, 0.9)", # Creamy white snow color
114
+ border_color_primary="#D4AF37", # Gold Border
115
+ button_primary_background_fill="#C62828", # Santa Red
116
+ button_primary_text_color="white",
117
+ )
118
+
119
+ # 2. CSS: Background image + Festive Styling
120
+ custom_css = """
121
+ /* Background: A cozy Christmas scene */
122
+ .gradio-container {
123
+ background: url('https://images.unsplash.com/photo-1544976735-a10c71a39644?q=80&w=2560&auto=format&fit=crop') no-repeat center center fixed;
124
+ background-size: cover;
125
+ }
126
+
127
+ /* Make main container transparent */
128
+ .gradio-container > .main {
129
+ background: transparent !important;
130
+ }
131
+
132
+ /* Chatbot Window - Glassy Snow Look */
133
+ .bubble-wrap {
134
+ background: rgba(255, 255, 255, 0.85) !important;
135
+ border: 2px solid #D4AF37 !important; /* Gold Border */
136
+ border-radius: 15px !important;
137
+ }
138
+
139
+ /* User Message - Christmas Red */
140
+ .user-message {
141
+ background-color: #D32F2F !important;
142
+ color: white !important;
143
+ border: 1px solid #B71C1C !important;
144
+ }
145
+
146
+ /* Bot Message - Christmas Green */
147
+ .bot-message {
148
+ background-color: #2E7D32 !important;
149
+ color: white !important;
150
+ border: 1px solid #1B5E20 !important;
151
+ }
152
+
153
+ /* Accordion/Settings - Snowy background with Gold border */
154
+ .group, .form {
155
+ background: rgba(255, 255, 255, 0.9) !important;
156
+ border: 2px solid #D4AF37 !important;
157
+ border-radius: 10px;
158
+ padding: 10px;
159
+ }
160
+
161
+ /* Labels */
162
+ label, span {
163
+ color: #3E2723 !important; /* Dark chocolate text for readability */
164
+ font-weight: bold;
165
+ }
166
+
167
+ footer {visibility: hidden}
168
+ """
169
+
170
+ # 4. Inputs (Only Max Tokens + Style)
171
+ max_new_tokens_slider = gr.Slider(
172
+ minimum=16, maximum=256, value=64, step=8, label="Max new tokens (Length)",
173
+ )
174
+
175
+ style_radio = gr.Radio(
176
+ choices=[
177
+ "Default",
178
+ "Short answer",
179
+ "Detailed explanation",
180
+ "Step-by-step reasoning",
181
+ ],
182
+ value="Detailed explanation",
183
+ label="Answer style",
184
+ )
185
+
186
+ # Instantiate ChatInterface
187
+ demo = gr.ChatInterface(
188
+ fn=chat_fn,
189
+ title="🎄 Holiday Chat Lab 2 🎅",
190
+ description="Chat with the fine-tuned model. Grab a hot chocolate and enjoy the holidays.",
191
+ additional_inputs=[
192
+ max_new_tokens_slider,
193
+ style_radio,
194
+ ],
195
+ additional_inputs_accordion="Holiday Settings",
196
+ )
197
+
198
+ # Apply Theme and CSS manually (Safe for older Gradio versions)
199
+ demo.theme = christmas_theme
200
+ demo.css = custom_css
201
+
202
+ if __name__ == "__main__":
203
+ demo.launch()
nikapp.py DELETED
@@ -1,166 +0,0 @@
1
- import gradio as gr
2
- import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer
4
-
5
- MODEL_ID = "Jeppcode/ScalableLab2"
6
- SUBFOLDER = "merged-model-fp16"
7
-
8
- print(f"Loading model {MODEL_ID}/{SUBFOLDER} ...")
9
-
10
- # Tokenizer
11
- tokenizer = AutoTokenizer.from_pretrained(
12
- MODEL_ID, subfolder=SUBFOLDER,
13
- )
14
-
15
- # Model – fp16 and optimized for CPU
16
- model = AutoModelForCausalLM.from_pretrained(
17
- MODEL_ID,
18
- subfolder=SUBFOLDER,
19
- dtype=torch.float16,
20
- low_cpu_mem_usage=True,
21
- device_map="cpu",
22
- )
23
- model.eval()
24
-
25
- # Hardcoded system prompt
26
- SYSTEM_PROMPT = "You are a helpful, polite assistant. Give clear and structured explanations."
27
-
28
- def build_prompt(message, history):
29
- messages = []
30
- messages.append({"role": "system", "content": SYSTEM_PROMPT})
31
-
32
- for msg in history:
33
- role = msg.get("role")
34
- content = msg.get("content", "")
35
- if isinstance(content, list):
36
- texts = []
37
- for block in content:
38
- if isinstance(block, dict) and block.get("type") == "text":
39
- texts.append(block.get("text", ""))
40
- else:
41
- texts.append(str(block))
42
- text = "\n".join(t for t in texts if t)
43
- else:
44
- text = str(content)
45
-
46
- if text and role in ("user", "assistant", "system"):
47
- messages.append({"role": role, "content": text})
48
-
49
- messages.append({"role": "user", "content": message})
50
-
51
- prompt = tokenizer.apply_chat_template(
52
- messages, tokenize=False, add_generation_prompt=True,
53
- )
54
- return prompt
55
-
56
- def chat_fn(message, history, max_new_tokens):
57
- prompt = build_prompt(message, history)
58
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
59
-
60
- # Default values
61
- temperature = 0.7
62
- top_p = 0.9
63
- repetition_penalty = 1.1
64
-
65
- gen_kwargs = {
66
- **inputs,
67
- "max_new_tokens": int(max_new_tokens),
68
- "pad_token_id": tokenizer.eos_token_id,
69
- "eos_token_id": tokenizer.eos_token_id,
70
- "repetition_penalty": float(repetition_penalty),
71
- "do_sample": True,
72
- "temperature": float(temperature),
73
- "top_p": float(top_p),
74
- }
75
-
76
- with torch.no_grad():
77
- outputs = model.generate(**gen_kwargs)
78
- generated = tokenizer.decode(
79
- outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True,
80
- ).strip()
81
-
82
- return generated
83
-
84
- # --- Visual Customization ---
85
-
86
- # 1. THEME: Set the base colors to forest greens
87
- nature_theme = gr.themes.Soft(
88
- primary_hue="green",
89
- secondary_hue="emerald",
90
- neutral_hue="stone",
91
- ).set(
92
- # Make the default backgrounds transparent or dark to blend with image
93
- body_background_fill="transparent",
94
- block_background_fill="rgba(20, 30, 20, 0.8)", # Dark semi-transparent green
95
- border_color_primary="#4CAF50", # Bright Green border
96
- input_background_fill="rgba(0, 0, 0, 0.5)",
97
- button_primary_background_fill="#2E7D32",
98
- text_color_subdued="#A5D6A7", # Light green text for labels
99
- )
100
-
101
- # 2. CSS: Force the background image and specific "Green Border" look
102
- custom_css = """
103
- /* The Main Forest Background */
104
- .gradio-container {
105
- background: url('https://images.unsplash.com/photo-1441974231531-c6227db76b6e?q=80&w=2560&auto=format&fit=crop') no-repeat center center fixed;
106
- background-size: cover;
107
- }
108
-
109
- /* Make the main App container transparent so background shows */
110
- .gradio-container > .main {
111
- background: transparent !important;
112
- }
113
-
114
- /* Chatbot Window Styling - The "Glassy" Look */
115
- .bubble-wrap {
116
- background: rgba(0, 0, 0, 0.6) !important;
117
- border: 1px solid #4CAF50 !important;
118
- border-radius: 10px !important;
119
- }
120
-
121
- /* User and Bot message bubbles */
122
- .user-message {
123
- background-color: #2E7D32 !important; /* Forest Green for user */
124
- border: 1px solid #66BB6A !important;
125
- }
126
- .bot-message {
127
- background-color: rgba(40, 40, 40, 0.9) !important; /* Dark Grey for bot */
128
- border: 1px solid #4CAF50 !important;
129
- }
130
-
131
- /* Input Area and Settings - Green Borders */
132
- .group, .form {
133
- background: rgba(10, 20, 10, 0.85) !important; /* Dark semi-transparent */
134
- border: 2px solid #4CAF50 !important; /* The prominent green border */
135
- border-radius: 8px;
136
- padding: 10px;
137
- }
138
-
139
- /* Text colors */
140
- label, span, p {
141
- color: #E8F5E9 !important; /* Very light green/white text */
142
- }
143
-
144
- /* Hide Footer */
145
- footer {visibility: hidden}
146
- """
147
-
148
- max_new_tokens_slider = gr.Slider(
149
- minimum=16, maximum=512, value=128, step=8, label="Response Length (Tokens)",
150
- )
151
-
152
- # Instantiate ChatInterface
153
- demo = gr.ChatInterface(
154
- fn=chat_fn,
155
- title="🌿 NatureChat Lab 2",
156
- description="Chat with the fine-tuned Llama model. Relax and enjoy the view.",
157
- additional_inputs=[max_new_tokens_slider],
158
- additional_inputs_accordion="Settings"
159
- )
160
-
161
- # Apply the Theme and CSS manually (Compatible with older Gradio versions)
162
- demo.theme = nature_theme
163
- demo.css = custom_css
164
-
165
- if __name__ == "__main__":
166
- demo.launch()