Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,93 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
#
|
|
|
|
|
|
|
| 6 |
MODEL_OPTIONS = {
|
| 7 |
-
"Phi-3.5 Mini Instruct": "microsoft/Phi-3.5-mini-instruct",
|
| 8 |
-
"Phi-3.5 MoE Instruct": "microsoft/Phi-3.5-MoE-instruct",
|
| 9 |
-
"Phi-3 Mini 4K Instruct": "microsoft/Phi-3-mini-4k-instruct",
|
| 10 |
-
"Phi-3 Mini 128K Instruct": "microsoft/Phi-3-mini-128k-instruct"
|
| 11 |
}
|
| 12 |
|
| 13 |
-
# Cache for loaded models
|
| 14 |
-
loaded_models = {}
|
| 15 |
-
|
| 16 |
EXAMPLES = [
|
| 17 |
-
"
|
| 18 |
-
"
|
| 19 |
-
"
|
| 20 |
-
"
|
| 21 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
]
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
def load_model(model_id):
|
| 26 |
-
if model_id
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
tokenizer, model = load_model(model_id)
|
| 41 |
|
| 42 |
-
messages = [
|
|
|
|
| 43 |
inputs = tokenizer.apply_chat_template(
|
| 44 |
messages,
|
| 45 |
add_generation_prompt=True,
|
| 46 |
tokenize=True,
|
| 47 |
-
return_dict=True,
|
| 48 |
return_tensors="pt"
|
| 49 |
).to("cpu")
|
| 50 |
|
|
|
|
| 51 |
with torch.no_grad():
|
| 52 |
outputs = model.generate(
|
| 53 |
**inputs,
|
| 54 |
-
max_new_tokens=
|
| 55 |
-
use_cache=False, # <— add this
|
| 56 |
do_sample=False,
|
| 57 |
-
|
| 58 |
-
top_p=0.9
|
| 59 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
# Gradio UI
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
model_choice = gr.Dropdown(
|
| 70 |
-
label="Choose a model",
|
| 71 |
-
choices=list(MODEL_OPTIONS.keys()),
|
| 72 |
-
value="Phi-3.5 Mini Instruct"
|
| 73 |
-
)
|
| 74 |
|
| 75 |
-
with gr.
|
| 76 |
-
|
|
|
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
import torch
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 8 |
|
| 9 |
+
# ----------------------------
|
| 10 |
+
# Config and defaults
|
| 11 |
+
# ----------------------------
|
| 12 |
MODEL_OPTIONS = {
|
| 13 |
+
"Phi-3.5 Mini Instruct (4B)": "microsoft/Phi-3.5-mini-instruct",
|
| 14 |
+
"Phi-3.5 MoE Instruct (42B)": "microsoft/Phi-3.5-MoE-instruct",
|
| 15 |
+
"Phi-3 Mini 4K Instruct (4B)": "microsoft/Phi-3-mini-4k-instruct",
|
| 16 |
+
"Phi-3 Mini 128K Instruct (4B)": "microsoft/Phi-3-mini-128k-instruct"
|
| 17 |
}
|
| 18 |
|
|
|
|
|
|
|
|
|
|
| 19 |
EXAMPLES = [
|
| 20 |
+
"Read this short passage and tell me the main idea in your own words.",
|
| 21 |
+
"I’ll teach you a concept. Repeat it back to me in simple words: Solar panels turn sunlight into electricity.",
|
| 22 |
+
"Here’s a new phrase: 'The sea is calm today.' Try saying it in Basque.",
|
| 23 |
+
"I’ll give you a style: noir detective. Write one sentence about Gros in that style.",
|
| 24 |
+
"Read a Shakespeare quote and tell me what you think it means.",
|
| 25 |
+
"Read a Dickens passage and explain how it feels.",
|
| 26 |
+
"Translate a short poem line into another language, then tell me what mood it carries.",
|
| 27 |
+
"Summarize this text in two sentences, then say if it sounds optimistic or pessimistic."
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
DEFAULT_PROFILE = {
|
| 31 |
+
"name": "Learner",
|
| 32 |
+
"style": ["concise", "reflective", "Basque context where relevant"],
|
| 33 |
+
"goals": ["conversation-first learning", "daily language blocks", "CPU-only"]
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
DEFAULT_BLOCKS = [
|
| 37 |
+
{"type": "style", "rule": "Ask clarifying questions when uncertain."},
|
| 38 |
+
{"type": "vocab", "rule": "Use sensory detail + local place anchoring when writing creatively."},
|
| 39 |
+
{"type": "conversation", "rule": "Keep answers short and specific; avoid repeating conclusions."}
|
| 40 |
]
|
| 41 |
|
| 42 |
+
BLOCKS_FILE = "blocks.json"
|
| 43 |
+
|
| 44 |
+
# ----------------------------
|
| 45 |
+
# Persistence helpers
|
| 46 |
+
# ----------------------------
|
| 47 |
+
def load_blocks():
|
| 48 |
+
if os.path.exists(BLOCKS_FILE):
|
| 49 |
+
try:
|
| 50 |
+
with open(BLOCKS_FILE, "r", encoding="utf-8") as f:
|
| 51 |
+
return json.load(f)
|
| 52 |
+
except Exception:
|
| 53 |
+
pass
|
| 54 |
+
return {"user_profile": DEFAULT_PROFILE, "language_blocks": DEFAULT_BLOCKS}
|
| 55 |
+
|
| 56 |
+
def save_blocks(data):
|
| 57 |
+
with open(BLOCKS_FILE, "w", encoding="utf-8") as f:
|
| 58 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 59 |
+
|
| 60 |
+
def add_block(data, rule_text, block_type="conversation"):
|
| 61 |
+
if not rule_text.strip():
|
| 62 |
+
return data
|
| 63 |
+
entry = {
|
| 64 |
+
"type": block_type,
|
| 65 |
+
"rule": rule_text.strip(),
|
| 66 |
+
"validated": True,
|
| 67 |
+
"review_schedule": schedule_reviews()
|
| 68 |
+
}
|
| 69 |
+
data["language_blocks"].append(entry)
|
| 70 |
+
save_blocks(data)
|
| 71 |
+
return data
|
| 72 |
+
|
| 73 |
+
def schedule_reviews():
|
| 74 |
+
today = datetime.utcnow().date()
|
| 75 |
+
return [
|
| 76 |
+
str(today + timedelta(days=1)),
|
| 77 |
+
str(today + timedelta(days=3)),
|
| 78 |
+
str(today + timedelta(days=7))
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
# ----------------------------
|
| 82 |
+
# Model loading (CPU-only)
|
| 83 |
+
# ----------------------------
|
| 84 |
+
_loaded = {} # cache
|
| 85 |
+
|
| 86 |
def load_model(model_id):
|
| 87 |
+
if model_id in _loaded:
|
| 88 |
+
return _loaded[model_id]
|
| 89 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 90 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 91 |
+
model_id,
|
| 92 |
+
trust_remote_code=True,
|
| 93 |
+
torch_dtype=torch.float32 # CPU friendly
|
| 94 |
+
)
|
| 95 |
+
model.eval()
|
| 96 |
+
_loaded[model_id] = (tokenizer, model)
|
| 97 |
+
return tokenizer, model
|
| 98 |
+
|
| 99 |
+
# ----------------------------
|
| 100 |
+
# Prompt construction
|
| 101 |
+
# ----------------------------
|
| 102 |
+
def format_blocks(blocks):
|
| 103 |
+
return "\n".join([f"- [{b.get('type','rule')}] {b.get('rule','')}" for b in blocks])
|
| 104 |
+
|
| 105 |
+
SYSTEM_TEMPLATE = """You are a conversation-first learning chatbot.
|
| 106 |
+
Follow the user's style and goals, reinforce today's blocks, and confirm corrections.
|
| 107 |
+
User style: {style}
|
| 108 |
+
Goals: {goals}
|
| 109 |
+
Active language blocks:
|
| 110 |
+
{blocks}
|
| 111 |
+
Guidelines:
|
| 112 |
+
- Keep responses concise and specific.
|
| 113 |
+
- Ask for clarification when needed.
|
| 114 |
+
- Extract new patterns only when validated by the user.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
def build_messages(user_text, profile, blocks):
|
| 118 |
+
system = SYSTEM_TEMPLATE.format(
|
| 119 |
+
style=", ".join(profile.get("style", [])),
|
| 120 |
+
goals=", ".join(profile.get("goals", [])),
|
| 121 |
+
blocks=format_blocks(blocks)
|
| 122 |
+
)
|
| 123 |
+
return [
|
| 124 |
+
{"role": "system", "content": system},
|
| 125 |
+
{"role": "user", "content": user_text}
|
| 126 |
+
]
|
| 127 |
|
| 128 |
+
# ----------------------------
|
| 129 |
+
# Generate (with token/latency)
|
| 130 |
+
# ----------------------------
|
| 131 |
+
def chat(user_text, model_label, blocks_json):
|
| 132 |
+
# parse blocks from textarea (JSON or fallback lines)
|
| 133 |
+
data = load_blocks()
|
| 134 |
+
blocks = parse_blocks_editor(blocks_json, data.get("language_blocks", []))
|
| 135 |
+
|
| 136 |
+
model_id = MODEL_OPTIONS[model_label]
|
| 137 |
tokenizer, model = load_model(model_id)
|
| 138 |
|
| 139 |
+
messages = build_messages(user_text, data["user_profile"], blocks)
|
| 140 |
+
|
| 141 |
inputs = tokenizer.apply_chat_template(
|
| 142 |
messages,
|
| 143 |
add_generation_prompt=True,
|
| 144 |
tokenize=True,
|
|
|
|
| 145 |
return_tensors="pt"
|
| 146 |
).to("cpu")
|
| 147 |
|
| 148 |
+
start = time.time()
|
| 149 |
with torch.no_grad():
|
| 150 |
outputs = model.generate(
|
| 151 |
**inputs,
|
| 152 |
+
max_new_tokens=200,
|
|
|
|
| 153 |
do_sample=False,
|
| 154 |
+
use_cache=False # Avoid DynamicCache mismatch issues on some setups
|
|
|
|
| 155 |
)
|
| 156 |
+
latency = time.time() - start
|
| 157 |
+
|
| 158 |
+
# slice out the generated continuation
|
| 159 |
+
gen_text = tokenizer.decode(
|
| 160 |
+
outputs[0][inputs["input_ids"].shape[-1]:],
|
| 161 |
+
skip_special_tokens=True
|
| 162 |
+
).strip()
|
| 163 |
+
|
| 164 |
+
# token counts
|
| 165 |
+
input_tokens = int(inputs["input_ids"].shape[-1])
|
| 166 |
+
output_tokens = int(outputs[0].shape[-1] - inputs["input_ids"].shape[-1])
|
| 167 |
+
|
| 168 |
+
metrics = f"Input tokens: {input_tokens} | Output tokens: {output_tokens} | Latency: {latency:.2f}s"
|
| 169 |
+
return gen_text, metrics
|
| 170 |
|
| 171 |
+
def parse_blocks_editor(text, fallback):
|
| 172 |
+
"""
|
| 173 |
+
Accept either:
|
| 174 |
+
- JSON array of blocks
|
| 175 |
+
- Plain text lines ("type: rule")
|
| 176 |
+
"""
|
| 177 |
+
if not text or not text.strip():
|
| 178 |
+
return fallback
|
| 179 |
+
text = text.strip()
|
| 180 |
+
try:
|
| 181 |
+
parsed = json.loads(text)
|
| 182 |
+
if isinstance(parsed, list):
|
| 183 |
+
return parsed
|
| 184 |
+
except Exception:
|
| 185 |
+
pass
|
| 186 |
+
# Fallback: each non-empty line becomes a block
|
| 187 |
+
blocks = []
|
| 188 |
+
for line in text.splitlines():
|
| 189 |
+
line = line.strip()
|
| 190 |
+
if not line:
|
| 191 |
+
continue
|
| 192 |
+
if ":" in line:
|
| 193 |
+
t, r = line.split(":", 1)
|
| 194 |
+
blocks.append({"type": t.strip(), "rule": r.strip()})
|
| 195 |
+
else:
|
| 196 |
+
blocks.append({"type": "rule", "rule": line})
|
| 197 |
+
return blocks or fallback
|
| 198 |
|
| 199 |
+
# ----------------------------
|
| 200 |
+
# Reflection: extract new rule
|
| 201 |
+
# ----------------------------
|
| 202 |
+
REFLECT_TEMPLATE = """From the user's last message and your reply, extract ONE reusable conversation rule.
|
| 203 |
+
Return only the rule, no preface, max 20 words.
|
| 204 |
+
Example rules:
|
| 205 |
+
- Ask clarifying questions when uncertain.
|
| 206 |
+
- Use sensory detail with local anchors in creative writing.
|
| 207 |
+
- Summarize then assess tone (optimistic/pessimistic).
|
| 208 |
+
User said:
|
| 209 |
+
{user}
|
| 210 |
+
Assistant replied:
|
| 211 |
+
{assistant}
|
| 212 |
+
Now output one new rule:"""
|
| 213 |
+
|
| 214 |
+
def reflect_and_save(user_text, assistant_text, blocks_editor_value):
|
| 215 |
+
data = load_blocks()
|
| 216 |
+
# Propose a rule via a simple heuristic (no extra model call, keeps it lean)
|
| 217 |
+
# If you prefer model-based reflection, you can run a generation with REFLECT_TEMPLATE.
|
| 218 |
+
proposal = heuristic_rule(user_text, assistant_text)
|
| 219 |
+
data = add_block(data, proposal, block_type="conversation")
|
| 220 |
+
|
| 221 |
+
# Return updated blocks as pretty JSON to show in the editor
|
| 222 |
+
pretty = json.dumps(data["language_blocks"], ensure_ascii=False, indent=2)
|
| 223 |
+
return pretty, f"Saved rule: {proposal}"
|
| 224 |
+
|
| 225 |
+
def heuristic_rule(user_text, assistant_text):
|
| 226 |
+
# Very simple heuristic: if assistant asked a question, reinforce clarification;
|
| 227 |
+
# otherwise, reinforce concise responses.
|
| 228 |
+
if "?" in assistant_text:
|
| 229 |
+
return "Ask clarifying questions when uncertain."
|
| 230 |
+
# If user asked for style or translation, capture that
|
| 231 |
+
low = user_text.lower()
|
| 232 |
+
if "translate" in low:
|
| 233 |
+
return "Confirm translation intent and target tone before translating."
|
| 234 |
+
if "style" in low or "noir" in low:
|
| 235 |
+
return "Confirm style constraints before writing and keep it concise."
|
| 236 |
+
return "Keep answers short, specific, and avoid repeating conclusions."
|
| 237 |
+
|
| 238 |
+
# ----------------------------
|
| 239 |
# Gradio UI
|
| 240 |
+
# ----------------------------
|
| 241 |
+
def launch():
|
| 242 |
+
data = load_blocks()
|
| 243 |
+
default_blocks_text = json.dumps(data["language_blocks"], ensure_ascii=False, indent=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
+
with gr.Blocks(title="Conversation Learning Lab (CPU)") as demo:
|
| 246 |
+
gr.Markdown("# 🗣️ Conversation Learning Lab (CPU-friendly)")
|
| 247 |
+
gr.Markdown("Focus on daily dialogue. Reinforce validated language blocks. Transparent tokens and latency.")
|
| 248 |
|
| 249 |
+
with gr.Row():
|
| 250 |
+
model_dd = gr.Dropdown(
|
| 251 |
+
label="Choose a model",
|
| 252 |
+
choices=list(MODEL_OPTIONS.keys()),
|
| 253 |
+
value="Phi-3.5 Mini Instruct (4B)"
|
| 254 |
+
)
|
| 255 |
|
| 256 |
+
with gr.Row():
|
| 257 |
+
user_in = gr.Textbox(
|
| 258 |
+
label="Your message",
|
| 259 |
+
placeholder="Start a conversation or choose an example below...",
|
| 260 |
+
lines=3
|
| 261 |
+
)
|
| 262 |
|
| 263 |
+
with gr.Row():
|
| 264 |
+
blocks_editor = gr.Textbox(
|
| 265 |
+
label="Today's blocks (JSON array or 'type: rule' lines)",
|
| 266 |
+
value=default_blocks_text,
|
| 267 |
+
lines=10
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
with gr.Row():
|
| 271 |
+
generate_btn = gr.Button("Generate (CPU)")
|
| 272 |
+
reflect_btn = gr.Button("Reflect & Save Rule")
|
| 273 |
+
|
| 274 |
+
with gr.Row():
|
| 275 |
+
output = gr.Textbox(label="Assistant", lines=8)
|
| 276 |
+
with gr.Row():
|
| 277 |
+
metrics = gr.Markdown("")
|
| 278 |
+
|
| 279 |
+
gr.Markdown("### 🧪 Try an example prompt:")
|
| 280 |
+
gr.Examples(
|
| 281 |
+
examples=EXAMPLES,
|
| 282 |
+
inputs=user_in
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
# Wire up events
|
| 286 |
+
generate_btn.click(
|
| 287 |
+
fn=chat,
|
| 288 |
+
inputs=[user_in, model_dd, blocks_editor],
|
| 289 |
+
outputs=[output, metrics]
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
reflect_btn.click(
|
| 293 |
+
fn=reflect_and_save,
|
| 294 |
+
inputs=[user_in, output, blocks_editor],
|
| 295 |
+
outputs=[blocks_editor, metrics]
|
| 296 |
+
)
|
| 297 |
|
| 298 |
+
demo.launch()
|
| 299 |
|
| 300 |
+
if __name__ == "__main__":
|
| 301 |
+
launch()
|