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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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",
    "huihui-ai/Huihui-Qwen3.5-9B-abliterated",
)
# 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="Qwen3.5-9B Multimodal",
    fill_height=True,
    theme=gr.themes.Soft(),
) as demo:
    gr.Markdown(
        "# huihui-ai/Huihui-Qwen3.5-9B-abliterated\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.5-9B",
        ),
        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)