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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
|
| 16 |
-
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Refactored Salama Assistant: text-only chatbot (STT and TTS removed)
|
| 4 |
+
Drop this file into your Hugging Face Space (replace existing app.py) or run locally.
|
| 5 |
+
Requirements:
|
| 6 |
+
- transformers
|
| 7 |
+
- peft
|
| 8 |
+
- gradio
|
| 9 |
+
- huggingface_hub
|
| 10 |
+
- torch
|
| 11 |
|
| 12 |
+
Notes:
|
| 13 |
+
- Set HF_TOKEN in env for private models or use Spaces secret.
|
| 14 |
+
- This keeps the LLM + PEFT adapter loading and streaming text responses into the Gradio chat UI.
|
| 15 |
"""
|
|
|
|
| 16 |
|
| 17 |
+
import os
|
| 18 |
+
import threading
|
| 19 |
+
import gradio as gr
|
| 20 |
+
import torch
|
| 21 |
+
from huggingface_hub import login
|
| 22 |
+
from transformers import (
|
| 23 |
+
AutoTokenizer,
|
| 24 |
+
AutoModelForCausalLM,
|
| 25 |
+
pipeline,
|
| 26 |
+
TextIteratorStreamer,
|
| 27 |
+
)
|
| 28 |
+
from peft import PeftModel, PeftConfig
|
| 29 |
+
|
| 30 |
+
# -------------------- Configuration --------------------
|
| 31 |
+
ADAPTER_REPO_ID = "EYEDOL/Llama-3.2-3b_ON_ALPACA5" # adapter-only repo
|
| 32 |
+
BASE_MODEL_ID = "unsloth/Llama-3.2-3B-Instruct" # full base model referenced by adapter
|
| 33 |
+
|
| 34 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("hugface")
|
| 35 |
+
if HF_TOKEN:
|
| 36 |
+
try:
|
| 37 |
+
login(token=HF_TOKEN)
|
| 38 |
+
print("Successfully logged into Hugging Face Hub!")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print("Warning: huggingface_hub.login() failed:", e)
|
| 41 |
+
else:
|
| 42 |
+
print("Warning: HF_TOKEN not found in env. Private repos may fail to load.")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class WeeboAssistant:
|
| 46 |
+
def __init__(self):
|
| 47 |
+
self.SYSTEM_PROMPT = (
|
| 48 |
+
"Wewe ni msaidizi mwenye akili, jibu swali lililoulizwa KWA UFUPI na kwa usahihi. "
|
| 49 |
+
"Jibu kwa lugha ya Kiswahili pekee. Hakuna jibu refu.\n"
|
| 50 |
+
)
|
| 51 |
+
self._init_models()
|
| 52 |
+
|
| 53 |
+
def _init_models(self):
|
| 54 |
+
print("Initializing models...")
|
| 55 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 56 |
+
self.torch_dtype = torch.bfloat16 if self.device == "cuda" else torch.float32
|
| 57 |
+
print(f"Using device: {self.device}")
|
| 58 |
+
|
| 59 |
+
# 1) Tokenizer (prefer base tokenizer)
|
| 60 |
+
try:
|
| 61 |
+
self.llm_tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, use_fast=True)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print("Warning: could not load base tokenizer, falling back to adapter tokenizer. Error:", e)
|
| 64 |
+
self.llm_tokenizer = AutoTokenizer.from_pretrained(ADAPTER_REPO_ID, use_fast=True)
|
| 65 |
+
|
| 66 |
+
# 2) Load base model
|
| 67 |
+
device_map = "auto" if torch.cuda.is_available() else None
|
| 68 |
+
try:
|
| 69 |
+
self.llm_model = AutoModelForCausalLM.from_pretrained(
|
| 70 |
+
BASE_MODEL_ID,
|
| 71 |
+
torch_dtype=self.torch_dtype,
|
| 72 |
+
low_cpu_mem_usage=True,
|
| 73 |
+
device_map=device_map,
|
| 74 |
+
trust_remote_code=True,
|
| 75 |
+
)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
raise RuntimeError(
|
| 78 |
+
"Failed to load base model. Ensure the base model ID is correct and the HF_TOKEN has access if private. Error: "
|
| 79 |
+
+ str(e)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# 3) Load and apply PEFT adapter (adapter-only repo)
|
| 83 |
+
try:
|
| 84 |
+
peft_config = PeftConfig.from_pretrained(ADAPTER_REPO_ID)
|
| 85 |
+
self.llm_model = PeftModel.from_pretrained(
|
| 86 |
+
self.llm_model,
|
| 87 |
+
ADAPTER_REPO_ID,
|
| 88 |
+
device_map=device_map,
|
| 89 |
+
torch_dtype=self.torch_dtype,
|
| 90 |
+
low_cpu_mem_usage=True,
|
| 91 |
+
)
|
| 92 |
+
except Exception as e:
|
| 93 |
+
raise RuntimeError(
|
| 94 |
+
"Failed to load/apply PEFT adapter from adapter repo. Make sure adapter files are present and HF_TOKEN has access if private. Error: "
|
| 95 |
+
+ str(e)
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# 4) Optional non-streaming pipeline (useful for small tests)
|
| 99 |
+
try:
|
| 100 |
+
device_index = 0 if torch.cuda.is_available() else -1
|
| 101 |
+
self.llm_pipeline = pipeline(
|
| 102 |
+
"text-generation",
|
| 103 |
+
model=self.llm_model,
|
| 104 |
+
tokenizer=self.llm_tokenizer,
|
| 105 |
+
device=device_index,
|
| 106 |
+
model_kwargs={"torch_dtype": self.torch_dtype},
|
| 107 |
+
)
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print("Warning: could not create text-generation pipeline. Streaming generate will still work. Error:", e)
|
| 110 |
+
self.llm_pipeline = None
|
| 111 |
+
|
| 112 |
+
print("LLM base + adapter loaded successfully.")
|
| 113 |
+
|
| 114 |
+
def get_llm_response(self, chat_history):
|
| 115 |
+
# Build prompt from system + conversation history
|
| 116 |
+
prompt_lines = [self.SYSTEM_PROMPT]
|
| 117 |
+
for user_msg, assistant_msg in chat_history:
|
| 118 |
+
if user_msg:
|
| 119 |
+
prompt_lines.append("User: " + user_msg)
|
| 120 |
+
if assistant_msg:
|
| 121 |
+
prompt_lines.append("Assistant: " + assistant_msg)
|
| 122 |
+
prompt_lines.append("Assistant: ")
|
| 123 |
+
prompt = "\n".join(prompt_lines)
|
| 124 |
+
|
| 125 |
+
inputs = self.llm_tokenizer(prompt, return_tensors="pt")
|
| 126 |
+
try:
|
| 127 |
+
model_device = next(self.llm_model.parameters()).device
|
| 128 |
+
except StopIteration:
|
| 129 |
+
model_device = torch.device("cpu")
|
| 130 |
+
inputs = {k: v.to(model_device) for k, v in inputs.items()}
|
| 131 |
+
|
| 132 |
+
streamer = TextIteratorStreamer(self.llm_tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 133 |
+
|
| 134 |
+
generation_kwargs = dict(
|
| 135 |
+
input_ids=inputs["input_ids"],
|
| 136 |
+
attention_mask=inputs.get("attention_mask", None),
|
| 137 |
+
max_new_tokens=512,
|
| 138 |
+
do_sample=True,
|
| 139 |
+
temperature=0.6,
|
| 140 |
+
top_p=0.9,
|
| 141 |
+
streamer=streamer,
|
| 142 |
+
eos_token_id=getattr(self.llm_tokenizer, "eos_token_id", None),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
gen_thread = threading.Thread(target=self.llm_model.generate, kwargs=generation_kwargs, daemon=True)
|
| 146 |
+
gen_thread.start()
|
| 147 |
+
|
| 148 |
+
return streamer
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# -------------------- Create assistant instance --------------------
|
| 152 |
+
assistant = WeeboAssistant()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# -------------------- Gradio pipelines --------------------
|
| 156 |
+
def t2t_pipeline(text_input, chat_history):
|
| 157 |
+
# Append the user's message and stream the assistant reply
|
| 158 |
+
chat_history.append((text_input, ""))
|
| 159 |
+
yield chat_history
|
| 160 |
+
|
| 161 |
+
response_stream = assistant.get_llm_response(chat_history)
|
| 162 |
+
llm_response_text = ""
|
| 163 |
+
for text_chunk in response_stream:
|
| 164 |
+
llm_response_text += text_chunk
|
| 165 |
+
chat_history[-1] = (text_input, llm_response_text)
|
| 166 |
+
yield chat_history
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def clear_textbox():
|
| 170 |
+
return gr.Textbox.update(value="")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# -------------------- Gradio UI --------------------
|
| 174 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Msaidizi wa Kiswahili - Text Chat") as demo:
|
| 175 |
+
gr.Markdown("# 🤖 Msaidizi wa Kiswahili (Text Chat)")
|
| 176 |
+
gr.Markdown("Ongea (aina ya maandishi) na msaidizi kwa Kiswahili. Tumia kisanduku kifuatacho kuandika.")
|
| 177 |
+
|
| 178 |
+
t2t_chatbot = gr.Chatbot(label="Mazungumzo (Conversation)", bubble_full_width=False, height=500)
|
| 179 |
+
with gr.Row():
|
| 180 |
+
t2t_text_in = gr.Textbox(show_label=False, placeholder="Andika hapa...", scale=4, container=False)
|
| 181 |
+
t2t_submit_btn = gr.Button("Tuma (Submit)", variant="primary", scale=1)
|
| 182 |
+
|
| 183 |
+
t2t_submit_btn.click(
|
| 184 |
+
fn=t2t_pipeline,
|
| 185 |
+
inputs=[t2t_text_in, t2t_chatbot],
|
| 186 |
+
outputs=[t2t_chatbot],
|
| 187 |
+
queue=True,
|
| 188 |
+
).then(
|
| 189 |
+
fn=clear_textbox,
|
| 190 |
+
inputs=None,
|
| 191 |
+
outputs=t2t_text_in,
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
t2t_text_in.submit(
|
| 195 |
+
fn=t2t_pipeline,
|
| 196 |
+
inputs=[t2t_text_in, t2t_chatbot],
|
| 197 |
+
outputs=[t2t_chatbot],
|
| 198 |
+
queue=True,
|
| 199 |
+
).then(
|
| 200 |
+
fn=clear_textbox,
|
| 201 |
+
inputs=None,
|
| 202 |
+
outputs=t2t_text_in,
|
| 203 |
+
)
|
| 204 |
|
|
|
|
|
|
|
| 205 |
|
| 206 |
+
demo.queue().launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|