Views
No views yet
transformersaccelerateqwen-vl-utils1pip install -U transformers accelerate torch torchvision
2# @title 🎭 Maggie VL: Flexible Storyteller (Text & Image)
3import json, os, torch, gc
4from PIL import Image
5from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
6
7# --- 1. KONFIGURASI ---
8PROMPT_BARU = "maggie duduk di teras rumah, menatap senja di Kerajaan Alghafar"
9IMAGE_PATH = "" # Path gambar (opsional)
10RESET_HISTORY = False
11
12MODEL_ID = "Maggie-32B-FP8-Instruct-abliterated"
13FILE = "maggie_history_cerita.json"
14
15SYSTEM_INS = """Nama: Maggie. Umur: 19 tahun.
16Fisik: Paras cantik luar biasa, rambut pirang platina, tinggi 165cm, berat 45kg, ramping.
17Latar: Putri Edward (pedagang kain). Tinggal di Kerajaan Alghafar.
18Sifat: Sopan namun memiliki ketegasan khas kelas menengah ke atas."""
19
20# --- 2. LOAD MODEL (Singleton Pattern) ---
21if 'model' not in globals():
22 gpu_name = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU"
23 print(f"🚀 [SYSTEM]: Mengaktifkan Maggie 32B di {gpu_name}...")
24 model = Qwen3VLForConditionalGeneration.from_pretrained(
25 MODEL_ID, device_map="auto", torch_dtype=torch.float16,
26 trust_remote_code=True, low_cpu_mem_usage=True
27 )
28 processor = AutoProcessor.from_pretrained(MODEL_ID)
29 print(f"✨ [SYSTEM]: {gpu_name} SIAP BERAKSI!\n")
30
31# --- 3. LOGIKA HISTORY ---
32if RESET_HISTORY and os.path.exists(FILE):
33 os.remove(FILE)
34 print("🧹 [HISTORY]: Catatan lama telah dihapus.")
35
36if os.path.exists(FILE):
37 with open(FILE, "r") as f: msg = json.load(f)
38else:
39 msg = [{"role": "system", "content": [{"type": "text", "text": SYSTEM_INS}]}]
40
41# Susun Konten User
42u_content = []
43img = None
44if IMAGE_PATH and os.path.exists(IMAGE_PATH):
45 img = Image.open(IMAGE_PATH).convert("RGB")
46 u_content.append({"type": "image", "image": img})
47u_content.append({"type": "text", "text": PROMPT_BARU})
48msg.append({"role": "user", "content": u_content})
49
50# --- 4. INFERENCE ---
51prompt_text = processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
52inputs = processor(text=[prompt_text], images=[img] if img else None, padding=True, return_tensors="pt").to(model.device)
53
54print(f"✍️ [qwen-32B]: Sedang menyusun adegan...")
55with torch.no_grad():
56 out_ids = model.generate(
57 **inputs,
58 max_new_tokens=1024,
59 temperature=0.7,
60 top_p=0.9,
61 do_sample=True,
62 repetition_penalty=1.1
63 )
64 resp = processor.batch_decode(out_ids[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)[0]
65
66# --- 5. CLEANUP & DISPLAY ---
67# Bersihkan memori sampah
68del inputs; torch.cuda.empty_cache(); gc.collect()
69
70print("\n" + "━"*60)
71print(f"📖 ADEGAN: {PROMPT_BARU.upper()}")
72print("━"*60)
73print(f"\n{resp.strip()}\n")
74print("━"*60)
75
76# Simpan History (Text-Only Mode)
77msg[-1] = {"role": "user", "content": [{"type": "text", "text": f"[Visual Input] {PROMPT_BARU}" if img else PROMPT_BARU}]}
78msg.append({"role": "assistant", "content": [{"type": "text", "text": resp}]})
79with open(FILE, "w") as f: json.dump(msg, f, indent=4)