wildfire_teller / app.py
hiko1999's picture
Switch to CPU execution
a5ccbbd
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import gradio as gr
from PIL import Image
# Hugging Face 模型仓库路径
model_path = "hiko1999/Qwen2-Wildfire-2B" # 替换为你的模型路径
# 加载 Hugging Face 上的模型和 processor
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = Qwen2VLForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.bfloat16) # 移除 device_map 参数以避免自动分配到 GPU
processor = AutoProcessor.from_pretrained(model_path)
# 定义预测函数
def predict(image):
# 将上传的图片处理为模型需要的格式
messages = [{"role": "user",
"content": [{"type": "image", "image": image}, {"type": "text", "text": "Describe this image."}]}]
# 处理图片输入
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
# 将数据转移到 CPU
inputs = inputs.to("cpu") # 使用 CPU 而不是 CUDA
# 生成模型输出
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True,
clean_up_tokenization_spaces=False)
return output_text[0] # 返回生成的文本
# Gradio界面
def gradio_interface(image):
result = predict(image)
return f"预测结果:{result}"
# 创建Gradio接口
interface = gr.Interface(fn=gradio_interface,
inputs=gr.Image(type="pil"), # 输入的图像
outputs="text", # 输出结果
title="火灾场景多模态模型预测",
description="上传图片进行火灾预测。")
# 启动接口
interface.launch()