LazyHuman10 commited on
Commit
277e6df
·
1 Parent(s): 57464eb

Switch to MiniCPM-V 4.6

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. model_engine.py +63 -46
  3. requirements.txt +1 -2
README.md CHANGED
@@ -37,7 +37,7 @@ This HuggingFace Space is built as a fast hackathon demo with a dark RPG web UI,
37
 
38
  ## Model
39
 
40
- NPCverse uses [`openbmb/MiniCPM-o-2_6-GPTQ`](https://huggingface.co/openbmb/MiniCPM-o-2_6-GPTQ), an 8B-class 4-bit GPTQ any-to-any model from OpenBMB. The model handles both visual analysis and character/chat generation through the HuggingFace Transformers integration.
41
 
42
  ## Badges
43
 
@@ -63,7 +63,7 @@ Open `http://localhost:7860` after the server starts.
63
 
64
  | Variable | Required | Notes |
65
  | --- | --- | --- |
66
- | `HF_TOKEN` | No | Not required for the public `openbmb/MiniCPM-o-2_6-GPTQ` model, but useful locally if you hit Hub rate limits or use private assets. |
67
 
68
  ## Hackathon
69
 
 
37
 
38
  ## Model
39
 
40
+ NPCverse uses [`openbmb/MiniCPM-V-4.6`](https://huggingface.co/openbmb/MiniCPM-V-4.6), a lightweight 1.3B image-text-to-text model from OpenBMB. The model handles both visual analysis and character/chat generation through the HuggingFace Transformers integration.
41
 
42
  ## Badges
43
 
 
63
 
64
  | Variable | Required | Notes |
65
  | --- | --- | --- |
66
+ | `HF_TOKEN` | No | Not required for the public `openbmb/MiniCPM-V-4.6` model, but useful locally if you hit Hub rate limits or use private assets. |
67
 
68
  ## Hackathon
69
 
model_engine.py CHANGED
@@ -1,7 +1,7 @@
1
  """AI model engine for NPCverse.
2
 
3
  NPCverse transforms uploaded photos into living RPG characters using
4
- MiniCPM-o GPTQ on Hugging Face ZeroGPU.
5
  """
6
 
7
  from __future__ import annotations
@@ -12,45 +12,17 @@ from typing import Any
12
 
13
  import spaces
14
  import torch
15
- from transformers import AutoModel, AutoTokenizer
16
- from transformers.modeling_utils import PreTrainedModel
17
  from PIL import Image
18
 
19
- MODEL_ID = "openbmb/MiniCPM-o-2_6-GPTQ"
20
 
21
-
22
- if not hasattr(PreTrainedModel, "all_tied_weights_keys"):
23
- def _normalize_tied_weights_keys(tied_keys: Any) -> dict:
24
- """Return tied weight keys in the dict shape expected by Transformers."""
25
- if tied_keys is None:
26
- return {}
27
- if isinstance(tied_keys, dict):
28
- return tied_keys
29
- return {key: None for key in tied_keys}
30
-
31
- @property
32
- def all_tied_weights_keys(self) -> dict:
33
- """Compatibility bridge for MiniCPM remote code on newer Transformers."""
34
- tied_keys = getattr(self, "_all_tied_weights_keys_compat", None)
35
- if tied_keys is None:
36
- tied_keys = getattr(self, "_tied_weights_keys", None)
37
- return _normalize_tied_weights_keys(tied_keys)
38
-
39
- @all_tied_weights_keys.setter
40
- def all_tied_weights_keys(self, tied_keys: Any) -> None:
41
- """Allow Transformers submodels to assign expanded tied weight keys."""
42
- self.__dict__["_all_tied_weights_keys_compat"] = tied_keys
43
-
44
- PreTrainedModel.all_tied_weights_keys = all_tied_weights_keys
45
-
46
-
47
- model = AutoModel.from_pretrained(
48
  MODEL_ID,
49
  trust_remote_code=True,
50
- attn_implementation="sdpa",
51
  dtype="auto",
52
  ).eval().to("cuda")
53
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
54
 
55
  FRIENDSHIP_THRESHOLDS = [10, 20, 35, 55]
56
  SECRET_THRESHOLDS = [8, 18, 35]
@@ -144,6 +116,38 @@ REQUIRED_STAT_KEYS = {
144
  }
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def parse_json_safe(text: str) -> dict:
148
  """Parse JSON after removing common markdown fences and wrapper text."""
149
  cleaned = re.sub(r"^\s*```(?:json)?\s*", "", text.strip(), flags=re.IGNORECASE)
@@ -219,9 +223,16 @@ def analyze_image(image_path: str) -> str:
219
  try:
220
  with Image.open(image_path) as image_obj:
221
  image_obj = image_obj.convert("RGB")
222
- msgs = [{'role': 'user', 'content': [image_obj, prompt_text]}]
223
- result = model.chat(image=None, msgs=msgs, tokenizer=tokenizer)
224
- return str(result).strip()
 
 
 
 
 
 
 
225
  except Exception:
226
  return "A mysterious figure in the digital realm."
227
 
@@ -277,13 +288,13 @@ No markdown. No extra text.
277
  def generate_npc(description: str) -> dict:
278
  """Generate a complete RPG NPC JSON object from a visual description."""
279
  try:
280
- msgs = [{'role': 'user', 'content': _npc_generation_prompt(description)}]
281
- result = model.chat(image=None, msgs=msgs, tokenizer=tokenizer)
282
  return _validate_npc_payload(parse_json_safe(str(result)))
283
  except Exception:
284
  try:
285
- retry_msgs = [{'role': 'user', 'content': _npc_retry_prompt(description)}]
286
- retry_result = model.chat(image=None, msgs=retry_msgs, tokenizer=tokenizer)
287
  return _validate_npc_payload(parse_json_safe(str(retry_result)))
288
  except Exception:
289
  return DEFAULT_NPC
@@ -368,13 +379,19 @@ Never say you are an AI model or break character.
368
  """.strip()
369
 
370
  msgs = [
371
- {"role": "user", "content": system_prompt},
372
- {"role": "assistant", "content": "Understood. I will remain fully in character."},
373
  ]
374
- msgs.extend(_normalize_history(history))
375
- msgs.append({"role": "user", "content": user_message})
376
-
377
- result = model.chat(image=None, msgs=msgs, tokenizer=tokenizer)
 
 
 
 
 
 
378
  return str(result).strip()
379
  except Exception:
380
  return f"*{npc_name} seems momentarily absent...*"
 
1
  """AI model engine for NPCverse.
2
 
3
  NPCverse transforms uploaded photos into living RPG characters using
4
+ MiniCPM-V 4.6 on Hugging Face ZeroGPU.
5
  """
6
 
7
  from __future__ import annotations
 
12
 
13
  import spaces
14
  import torch
15
+ from transformers import AutoModelForImageTextToText, AutoProcessor
 
16
  from PIL import Image
17
 
18
+ MODEL_ID = "openbmb/MiniCPM-V-4.6"
19
 
20
+ processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
21
+ model = AutoModelForImageTextToText.from_pretrained(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  MODEL_ID,
23
  trust_remote_code=True,
 
24
  dtype="auto",
25
  ).eval().to("cuda")
 
26
 
27
  FRIENDSHIP_THRESHOLDS = [10, 20, 35, 55]
28
  SECRET_THRESHOLDS = [8, 18, 35]
 
116
  }
117
 
118
 
119
+ def _generate_from_messages(
120
+ messages: list[dict[str, Any]],
121
+ max_new_tokens: int = 512,
122
+ downsample_mode: str = "16x",
123
+ ) -> str:
124
+ """Generate text with MiniCPM-V-4.6 from chat-template messages."""
125
+ inputs = processor.apply_chat_template(
126
+ messages,
127
+ tokenize=True,
128
+ add_generation_prompt=True,
129
+ return_dict=True,
130
+ return_tensors="pt",
131
+ downsample_mode=downsample_mode,
132
+ max_slice_nums=36,
133
+ ).to(model.device)
134
+ generated_ids = model.generate(
135
+ **inputs,
136
+ downsample_mode=downsample_mode,
137
+ max_new_tokens=max_new_tokens,
138
+ )
139
+ generated_ids_trimmed = [
140
+ output_ids[len(input_ids):]
141
+ for input_ids, output_ids in zip(inputs["input_ids"], generated_ids)
142
+ ]
143
+ output_text = processor.batch_decode(
144
+ generated_ids_trimmed,
145
+ skip_special_tokens=True,
146
+ clean_up_tokenization_spaces=False,
147
+ )
148
+ return str(output_text[0]).strip() if output_text else ""
149
+
150
+
151
  def parse_json_safe(text: str) -> dict:
152
  """Parse JSON after removing common markdown fences and wrapper text."""
153
  cleaned = re.sub(r"^\s*```(?:json)?\s*", "", text.strip(), flags=re.IGNORECASE)
 
223
  try:
224
  with Image.open(image_path) as image_obj:
225
  image_obj = image_obj.convert("RGB")
226
+ messages = [
227
+ {
228
+ "role": "user",
229
+ "content": [
230
+ {"type": "image", "image": image_obj},
231
+ {"type": "text", "text": prompt_text},
232
+ ],
233
+ }
234
+ ]
235
+ return _generate_from_messages(messages, max_new_tokens=180)
236
  except Exception:
237
  return "A mysterious figure in the digital realm."
238
 
 
288
  def generate_npc(description: str) -> dict:
289
  """Generate a complete RPG NPC JSON object from a visual description."""
290
  try:
291
+ msgs = [{'role': 'user', 'content': [{"type": "text", "text": _npc_generation_prompt(description)}]}]
292
+ result = _generate_from_messages(msgs, max_new_tokens=900)
293
  return _validate_npc_payload(parse_json_safe(str(result)))
294
  except Exception:
295
  try:
296
+ retry_msgs = [{'role': 'user', 'content': [{"type": "text", "text": _npc_retry_prompt(description)}]}]
297
+ retry_result = _generate_from_messages(retry_msgs, max_new_tokens=900)
298
  return _validate_npc_payload(parse_json_safe(str(retry_result)))
299
  except Exception:
300
  return DEFAULT_NPC
 
379
  """.strip()
380
 
381
  msgs = [
382
+ {"role": "user", "content": [{"type": "text", "text": system_prompt}]},
383
+ {"role": "assistant", "content": [{"type": "text", "text": "Understood. I will remain fully in character."}]},
384
  ]
385
+ for turn in _normalize_history(history):
386
+ msgs.append(
387
+ {
388
+ "role": turn["role"],
389
+ "content": [{"type": "text", "text": turn["content"]}],
390
+ }
391
+ )
392
+ msgs.append({"role": "user", "content": [{"type": "text", "text": user_message}]})
393
+
394
+ result = _generate_from_messages(msgs, max_new_tokens=320)
395
  return str(result).strip()
396
  except Exception:
397
  return f"*{npc_name} seems momentarily absent...*"
requirements.txt CHANGED
@@ -9,5 +9,4 @@ sentencepiece
9
  python-dotenv
10
  huggingface_hub>=0.24.0
11
  uvicorn>=0.30.0
12
- gptqmodel
13
- soundfile
 
9
  python-dotenv
10
  huggingface_hub>=0.24.0
11
  uvicorn>=0.30.0
12
+ av