onlyrickroll commited on
Commit
7b2e7fd
·
verified ·
1 Parent(s): a73ea4f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from huggingface_hub import hf_hub_download
4
+ from llama_cpp import Llama
5
+ from llama_cpp.llama_chat_format import LlavaChatHandler
6
+
7
+ # --- 配置模型信息 ---
8
+ # 建议使用 Qwen3-VL 的官方 GGUF 仓库
9
+ REPO_ID = "Qwen/Qwen3-VL-8B-Instruct-GGUF"
10
+ MODEL_FILE = "Qwen3-VL-8B-Instruct-Q4_K_M.gguf"
11
+ MMPROJ_FILE = "mmproj-Qwen3-VL-8B-Instruct-Q8_0.gguf"
12
+
13
+ print("正在下载/加载模型权重,请稍候...")
14
+ # 下载语言模型
15
+ model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILE)
16
+ # 下载视觉投影器 (mmproj)
17
+ mmproj_path = hf_hub_download(repo_id=REPO_ID, filename=MMPROJ_FILE)
18
+
19
+ # --- 初始化 Llama 实例 ---
20
+ # 关键:Qwen-VL 系列需要专用的 chat_handler 来处理图像输入
21
+ chat_handler = LlavaChatHandler(mmproj_path=mmproj_path)
22
+
23
+ llm = Llama(
24
+ model_path=model_path,
25
+ chat_handler=chat_handler,
26
+ n_ctx=2048, # 上下文窗口,若内存充足可设为 4096
27
+ n_threads=4, # 免费Space通常提供4个vCPU
28
+ logits_all=True,
29
+ n_gpu_layers=-1 if os.environ.get("SPACES_ZERO_GPU") else 0 # 如果有GPU则全量加速
30
+ )
31
+
32
+ def process_input(message, history):
33
+ """
34
+ 处理 Gradio 的多模态输入
35
+ message: {"text": "xxx", "files": ["path/to/img"]}
36
+ """
37
+ txt = message["text"]
38
+ files = message["files"]
39
+
40
+ prompt_messages = []
41
+
42
+ # 构建消息格式
43
+ user_content = [{"type": "text", "text": txt}]
44
+
45
+ if files:
46
+ # 处理图片输入
47
+ image_url = files[0] # 取第一张图
48
+ user_content.append({"type": "image_url", "image_url": {"url": image_url}})
49
+
50
+ # 构造 llama-cpp 的 chat 格式
51
+ response = llm.create_chat_completion(
52
+ messages=[{"role": "user", "content": user_content}],
53
+ max_tokens=512,
54
+ stream=False # 简单起见使用非流式,如需流式可改为 True 并 yield
55
+ )
56
+
57
+ return response["choices"][0]["message"]["content"]
58
+
59
+ # --- 构建 Gradio 界面 ---
60
+ with gr.Blocks() as demo:
61
+ gr.Markdown("# 🚀 Qwen3-VL 本地 GGUF 推理")
62
+ gr.Markdown("运行在 Space 本地资源上,支持图片分析。")
63
+
64
+ chatbot = gr.ChatInterface(
65
+ fn=process_input,
66
+ multimodal=True, # 开启多模态上传功能
67
+ type="messages",
68
+ )
69
+
70
+ if __name__ == "__main__":
71
+ demo.launch()