phi4-base / app.py
Kisho00's picture
Update app.py
4a15e70 verified
Raw History Blame Contribute Delete
3.54 kB
import json
import re
import spaces
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
MODEL_ID = "Kisho00/furi-phi4-mini-FINAL"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=torch.bfloat16,
device_map="auto",
)
# ---------- Scope check (temporary safety net until retraining) ----------
PET = re.compile(r"\b(dog|dogs|puppy|puppies|pup|canine|aso|tuta|cat|cats|kitten|kittens|kitty|feline|pusa|kuting|pet|pets)\b", re.I)
OTHER_ANIMAL = re.compile(r"\b(rabbit|bunny|hamster|guinea pig|parrot|budgie|bird|cockatiel|fish|goldfish|betta|turtle|tortoise|"
r"snake|lizard|gecko|iguana|ferret|chinchilla|hedgehog|rat|mouse|mice|horse|pony|cow|goat|pig|sheep|"
r"chicken|duck|axolotl|frog|spider|tarantula)\b", re.I)
OFF_TOPIC = re.compile(r"\b(python|javascript|code|coding|program|sql|essay|homework|poem|story|recipe|cook|bake|laptop|phone|"
r"stock|invest|crypto|tax|president|capital of|weather|movie|song|lyrics|translate|resume|cover letter|"
r"email to|my boss|workout|lose weight|headache|my back|breakup|system prompt|ignore your|instructions)\b", re.I)
DECLINE_ANIMAL = ("I only help with dogs and cats, so I can't advise on that animal. A vet who treats that kind of animal "
"is your best bet. I'm happy to help with any dog or cat question.")
DECLINE_OFF = ("I'm here to help with dog and cat care, so I can't help with that. "
"Is there anything about your dog or cat I can help with?")
def owner_question(messages):
"""The owner's latest question, without the [OWNER_PETS] block."""
for m in reversed(messages):
if m.get("role") == "user":
text = m.get("content", "")
if "Owner question:" in text:
return text.split("Owner question:", 1)[1].strip()
if "[/OWNER_PETS]" in text:
return text.split("[/OWNER_PETS]", 1)[1].strip()
return text.strip()
return ""
def scope_check(question: str):
"""A fixed decline message if the question is clearly out of scope, else None."""
has_pet = bool(PET.search(question))
if OTHER_ANIMAL.search(question) and not has_pet:
return DECLINE_ANIMAL
if OFF_TOPIC.search(question) and not has_pet:
return DECLINE_OFF
return None
# -------------------------------------------------------------------------
@spaces.GPU
def chat(messages_json: str, max_new_tokens: int = 400) -> str:
messages = json.loads(messages_json)
blocked = scope_check(owner_question(messages))
if blocked:
return blocked
inputs = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
return_dict=True,
).to(model.device)
output = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=True,
temperature=0.3, # was 0.7: lower = more consistent replies
top_p=0.9,
repetition_penalty=1.05,
)
reply = tokenizer.decode(
output[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True
)
return reply.strip()
demo = gr.Interface(
fn=chat,
inputs=[
gr.Textbox(label="messages_json"),
gr.Slider(16, 512, value=400, label="max_new_tokens"),
],
outputs=gr.Textbox(label="reply"),
)
demo.launch()