chatter / app.py
aertsimon90's picture
Update app.py
390609a verified
Raw History Blame Contribute Delete
17.2 kB
import os
import tempfile
from threading import Thread
import spaces
import torch
import gradio as gr
from PIL import Image
from transformers import (
AutoProcessor,
AutoModelForMultimodalLM,
BitsAndBytesConfig,
TextIteratorStreamer,
)
# ============================================================
# CONFIG
# ============================================================
MODEL_ID = os.environ.get(
"MODEL_ID",
"JonathanColetti/Qwen3.8-27B-Uncensored",
)
# 40-second maximum GPU reservation per generation
GPU_DURATION = 40
MAX_NEW_TOKENS = 4096
DEFAULT_TEMPERATURE = 1.0
DEFAULT_TOP_P = 0.95
DEFAULT_TOP_K = 20
DEFAULT_REASONING = "off"
REASONING_CHOICES = [
("Off — answer immediately", "off"),
("Low — brief thinking", "low"),
("Medium", "medium"),
("High", "xhigh"),
]
REASONING_INSTRUCTIONS = {
"low": (
"Reasoning effort is set to low. "
"Keep your thinking brief and focused."
),
"medium": "",
"xhigh": (
"Reasoning effort is set to high. "
"Think carefully, validate assumptions, and "
"prioritize correctness and clarity."
),
}
QUANTIZE = os.environ.get("QUANTIZE", "bf16").lower()
if not torch.cuda.is_available():
raise RuntimeError("CUDA GPU is required to run this application.")
# ============================================================
# MODEL LOADING
# ============================================================
load_kwargs = {
"dtype": torch.bfloat16,
"device_map": "cuda",
}
if QUANTIZE == "4bit":
load_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
print(f"[app] Loading model: {MODEL_ID}", flush=True)
print(f"[app] Quantization: {QUANTIZE}", flush=True)
print(f"[app] GPU reservation: {GPU_DURATION}s", flush=True)
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
MODEL_ID,
**load_kwargs,
)
model.eval()
tokenizer = getattr(processor, "tokenizer", processor)
# ============================================================
# IMAGE AND FILE HANDLING
# ============================================================
try:
import pillow_heif
pillow_heif.register_heif_opener()
HEIF_AVAILABLE = True
except ImportError:
HEIF_AVAILABLE = False
NATIVE_FORMATS = {"JPEG", "PNG", "WEBP", "GIF"}
SUPPORTED_HINT = (
"JPEG, PNG, WebP, GIF, BMP, TIFF, ICO"
+ (", HEIC/HEIF" if HEIF_AVAILABLE else "")
)
IMAGE_SUFFIXES = {
".jpg", ".jpeg", ".jpe", ".png", ".webp", ".gif",
".bmp", ".dib", ".tif", ".tiff", ".ico", ".ppm",
".pgm", ".pbm", ".tga", ".heic", ".heif", ".avif",
}
TEXT_SUFFIXES = {
".txt", ".text", ".md", ".markdown", ".rst", ".log",
".csv", ".tsv", ".json", ".jsonl", ".ndjson",
".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf",
".env", ".xml", ".html", ".htm", ".css", ".js",
".jsx", ".ts", ".tsx", ".py", ".pyi", ".c", ".h",
".cc", ".cpp", ".hpp", ".java", ".kt", ".go", ".rs",
".rb", ".php", ".swift", ".sh", ".bash", ".zsh",
".sql", ".r", ".jl", ".lua", ".pl", ".diff",
".patch", ".srt", ".vtt", ".tex",
}
MAX_FILE_CHARS = 30_000
_image_cache = {}
def prepare_image(path):
"""Validate and normalize an uploaded image."""
cached = _image_cache.get(path)
if cached and os.path.exists(cached):
return cached
name = os.path.basename(path or "file")
try:
with Image.open(path) as probe:
probe.verify()
with Image.open(path) as img:
fmt = (img.format or "").upper()
if fmt in NATIVE_FORMATS and img.mode in ("RGB", "L"):
_image_cache[path] = path
return path
converted = img.convert("RGB")
fd, output_path = tempfile.mkstemp(suffix=".png")
os.close(fd)
converted.save(output_path, format="PNG")
_image_cache[path] = output_path
return output_path
except Exception as exc:
raise gr.Error(
f"Couldn't read image '{name}'. "
f"Supported formats: {SUPPORTED_HINT}. "
"Try converting the image to JPEG or PNG."
) from exc
def looks_like_text(path):
"""Detect text attachments even when their extensions are unknown."""
try:
with open(path, "rb") as file:
head = file.read(8192)
except OSError:
return False
if b"\x00" in head:
return False
try:
head.decode("utf-8")
return True
except UnicodeDecodeError:
try:
head[:-4].decode("utf-8")
return True
except UnicodeDecodeError:
return False
def read_text_file(path):
"""Read an attachment with a context-size limit."""
name = os.path.basename(path or "file")
try:
with open(
path, "r", encoding="utf-8", errors="replace"
) as file:
body = file.read(MAX_FILE_CHARS + 1)
except OSError as exc:
raise gr.Error(
f"Couldn't read attachment '{name}'."
) from exc
if len(body) > MAX_FILE_CHARS:
body = body[:MAX_FILE_CHARS].rstrip() + "\n\n[... truncated]"
if name == "pasted_text.txt":
return body
return (
f"--- attached file: {name} ---\n"
f"{body}\n"
f"--- end of {name} ---"
)
def file_part(path):
"""Convert a path into a multimodal chat-template part."""
if not path:
return None
suffix = os.path.splitext(path)[1].lower()
if suffix in IMAGE_SUFFIXES:
return {
"type": "image",
"image": prepare_image(path),
}
if suffix in TEXT_SUFFIXES or looks_like_text(path):
return {
"type": "text",
"text": read_text_file(path),
}
return {
"type": "image",
"image": prepare_image(path),
}
def content_parts(content):
"""Normalize Gradio history content into message parts."""
if isinstance(content, tuple):
return [
part
for part in (file_part(item) for item in content)
if part
]
items = content if isinstance(content, list) else [content]
parts = []
for item in items:
if isinstance(item, str):
if item.strip():
parts.append({
"type": "text",
"text": item,
})
elif isinstance(item, dict):
if item.get("type") in ("text", "image"):
parts.append(item)
continue
path = item.get("path") or item.get("url")
part = file_part(path)
if part:
parts.append(part)
elif isinstance(item, (list, tuple)) and item:
part = file_part(item[0])
if part:
parts.append(part)
return parts
def to_messages(message, history):
"""Build the current conversation from Gradio history."""
messages = []
for turn in history or []:
if not isinstance(turn, dict):
continue
role = turn.get("role")
if role not in ("user", "assistant"):
continue
# Exclude reasoning-only bubbles and truncation notices.
metadata = turn.get("metadata") or {}
if metadata.get("title"):
continue
parts = content_parts(turn.get("content"))
if parts:
messages.append({
"role": role,
"content": parts,
})
parts = []
for path in message.get("files") or []:
if isinstance(path, dict):
path = path.get("path") or path.get("url")
part = file_part(path)
if part:
parts.append(part)
text = message.get("text") or ""
if text.strip():
parts.append({
"type": "text",
"text": text,
})
if not parts:
raise gr.Error(
"Nothing to send — type a message or attach a file."
)
messages.append({
"role": "user",
"content": parts,
})
return messages
# ============================================================
# REASONING DISPLAY
# ============================================================
THINKING_MARKERS = [
("<think>", "</think>"),
("[Start thinking]", "[End thinking]"),
]
def split_thinking(text, expect_thinking=True):
"""Separate reasoning markers from the user-facing answer."""
for opener, closer in THINKING_MARKERS:
if closer in text:
thought, _, answer = text.partition(closer)
thought = thought.replace(opener, "", 1).strip()
result = []
if thought:
result.append(
gr.ChatMessage(
role="assistant",
content=thought,
metadata={"title": "Reasoning"},
)
)
result.append(
gr.ChatMessage(
role="assistant",
content=answer.strip(),
)
)
return result
if opener in text:
thought = text.replace(opener, "", 1).strip()
return [
gr.ChatMessage(
role="assistant",
content=thought,
metadata={"title": "Reasoning"},
)
]
if expect_thinking:
return [
gr.ChatMessage(
role="assistant",
content=text,
metadata={"title": "Reasoning"},
)
]
return [
gr.ChatMessage(
role="assistant",
content=text,
)
]
# ============================================================
# CHAT GENERATION
# ============================================================
def respond(
message: dict,
history: list,
reasoning: str,
temperature: float,
top_p: float,
top_k: int,
):
messages = to_messages(message, history)
yield from generate(
messages,
reasoning,
temperature,
top_p,
top_k,
)
def gpu_duration(messages, reasoning=DEFAULT_REASONING, *args, **kwargs):
"""Reserve exactly 40 seconds for a generation task."""
return GPU_DURATION
@spaces.GPU(duration=gpu_duration, size="xlarge")
def generate(
messages: list,
reasoning: str,
temperature: float,
top_p: float,
top_k: int,
):
template_kwargs = {
"preserve_thinking": False,
}
if reasoning == "off":
template_kwargs["enable_thinking"] = False
else:
instruction = REASONING_INSTRUCTIONS.get(reasoning, "")
if instruction:
messages = [
{
"role": "system",
"content": [
{
"type": "text",
"text": instruction,
}
],
}
] + messages
try:
inputs = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
**template_kwargs,
).to(model.device)
except Exception as exc:
raise gr.Error(
"Failed to prepare the prompt. Check the installed "
"Transformers version and the model's chat template. "
f"Details: {exc}"
) from exc
streamer = TextIteratorStreamer(
tokenizer,
skip_prompt=True,
skip_special_tokens=True,
)
generation_kwargs = {
**inputs,
"streamer": streamer,
"max_new_tokens": MAX_NEW_TOKENS,
}
if temperature > 0:
generation_kwargs.update(
do_sample=True,
temperature=temperature,
top_p=top_p,
top_k=top_k,
)
else:
generation_kwargs["do_sample"] = False
failure = []
def run_generation():
try:
with torch.inference_mode():
model.generate(**generation_kwargs)
except Exception as exc:
failure.append(exc)
streamer.end()
thread = Thread(
target=run_generation,
daemon=True,
)
thread.start()
expect_thinking = reasoning != "off"
reply = ""
for chunk in streamer:
reply += chunk
yield split_thinking(
reply,
expect_thinking=expect_thinking,
)
thread.join()
if failure:
raise gr.Error(
f"Generation failed: {failure[0]}"
)
if not reply.strip():
yield [
gr.ChatMessage(
role="assistant",
content="_(The model returned an empty response.)_",
)
]
return
messages_out = split_thinking(
reply,
expect_thinking=expect_thinking,
)
generated = len(
tokenizer(
reply,
add_special_tokens=False,
).input_ids
)
if generated >= MAX_NEW_TOKENS - 4:
messages_out.append(
gr.ChatMessage(
role="assistant",
content=(
f"Reply reached the {MAX_NEW_TOKENS}-token limit. "
"Ask for a shorter answer or split the task."
),
metadata={
"title": "Reply may be truncated",
},
)
)
yield messages_out
# ============================================================
# EXAMPLES
# ============================================================
EXAMPLES = [
[
{
"text": (
"Explain SQL injection with a vulnerable example "
"and a regression test."
),
"files": [],
}
],
[
{
"text": (
"Help me write a realistic heist scene for a novel."
),
"files": [],
}
],
[
{
"text": (
"Explain the mechanisms and risks of common "
"over-the-counter drug interactions."
),
"files": [],
}
],
[
{
"text": (
"Write a menacing but PG-13 villain monologue."
),
"files": [],
}
],
[
{
"text": (
"Give me a blunt critique of a subscription service "
"that mails artisanal ice cubes."
),
"files": [],
}
],
]
# ============================================================
# GRADIO UI
# ============================================================
PRECISION_NOTE = (
"4-bit NF4"
if QUANTIZE == "4bit"
else "BF16"
)
with gr.Blocks(
title="Qwen 3.8 Uncensored",
fill_height=True,
theme=gr.themes.Soft(),
) as demo:
gr.Markdown(
"# JonathanColetti/Qwen3.8-27B-Uncensored\n"
"Multimodal chat with text and image uploads.\n\n"
f"Model: [`{MODEL_ID}`]"
f"(https://huggingface.co/{MODEL_ID}) · "
f"{PRECISION_NOTE} · "
f"GPU reservation: {GPU_DURATION}s"
)
with gr.Accordion("Sampling", open=False):
reasoning = gr.Dropdown(
choices=REASONING_CHOICES,
value=DEFAULT_REASONING,
label="Reasoning effort",
info=(
"Higher reasoning effort may consume the output "
"budget before the final answer."
),
)
temperature = gr.Slider(
minimum=0.0,
maximum=2.0,
value=DEFAULT_TEMPERATURE,
step=0.05,
label="Temperature",
)
top_p = gr.Slider(
minimum=0.0,
maximum=1.0,
value=DEFAULT_TOP_P,
step=0.01,
label="Top-p",
)
top_k = gr.Slider(
minimum=1,
maximum=100,
value=DEFAULT_TOP_K,
step=1,
label="Top-k",
)
gr.ChatInterface(
fn=respond,
multimodal=True,
chatbot=gr.Chatbot(
height="68vh",
resizable=True,
buttons=["copy", "copy_all"],
label="Qwen3.8-27B-Uncensored",
),
textbox=gr.MultimodalTextbox(
max_plain_text_length=100_000,
placeholder="Ask anything, or attach an image…",
show_label=False,
),
additional_inputs=[
reasoning,
temperature,
top_p,
top_k,
],
examples=EXAMPLES,
cache_examples=False,
)
if __name__ == "__main__":
demo.launch(mcp_server=True)