Spaces:
Sleeping
Sleeping
File size: 5,143 Bytes
81769c3 | 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 | import os
from typing import TypedDict, Annotated, Literal
import operator
import json
import pandas as pd
from IPython.display import Image, display
import soundfile as sf
from tqdm.notebook import tqdm
from pydantic import BaseModel
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_community.tools import WikipediaQueryRun, DuckDuckGoSearchRun
from langchain_core.tools import Tool
from langchain_experimental.utilities import PythonREPL
from langchain_ollama.chat_models import ChatOllama
from langchain_ollama.llms import OllamaLLM
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, AnyMessage, ToolMessage
from langgraph.graph.message import add_messages
from langgraph.graph import MessagesState, StateGraph, END, START, StateGraph
from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor
from qwen_omni_utils import process_mm_info
from utils import load_qa_data, GAIAQuestions, extract_json, submit
class QWEN2_5OmniModelRun:
def __init__(self, model_path: str = "./models/Qwen2.5-Omni-3B", local_files_only: bool = True, use_audio_in_video = False, return_audio = False):
self.model_path = model_path
self.use_audio_in_video = use_audio_in_video
self.return_audio = return_audio
self.model = Qwen2_5OmniForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto", device_map="auto", local_files_only=local_files_only)
self.model.disable_talker()
self.processor = Qwen2_5OmniProcessor.from_pretrained(model_path, local_files_only=local_files_only)
def __parse_messages(self, messages: list[AnyMessage], file_path: str | None = None, file_type: Literal["audio", "video", "image"] | None = None) -> list[dict]:
parsed_messages = []
for message in messages:
if isinstance(message, SystemMessage):
parsed_messages.append({"role": "system", "content": [{"type": "text", "text": message.content}]})
elif isinstance(message, HumanMessage):
parsed_messages.append({"role": "user", "content": [
{"type": file_type, file_type: file_path},
{"type": "text", "text": message.content},
] if file_type else [{"type": "text", "text": message.content}]})
elif isinstance(message, AIMessage):
parsed_messages.append({"role": "assistant", "content": [{"type": "text", "text": message.content}]})
elif isinstance(message, ToolMessage):
parsed_messages.append({"role": "assistant", "content": message.content})
return parsed_messages
def inference(self, messages: list[dict]) -> str:
# def inference(user_prompt: str, sys_prompt: str, file_path: str | None = None, file_type: Literal["audio", "video", "image"] | None = None) -> str:
# messages = [
# {"role": "system", "content": [{"type": "text", "text": sys_prompt}]},
# {"role": "user", "content": [
# {"type": file_type, file_type: file_path},
# {"type": "text", "text": user_prompt},
# ] if file_type else [{"type": "text", "text": user_prompt}]
# },
# ]
text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
audios, images, videos = process_mm_info(messages, use_audio_in_video=self.use_audio_in_video)
inputs = self.processor(text=text, audio=audios, images=images, videos=videos, return_tensors="pt", padding=True, use_audio_in_video=self.use_audio_in_video)
inputs = inputs.to(self.model.device).to(self.model.dtype)
output = self.model.generate(**inputs, use_audio_in_video=self.use_audio_in_video, return_audio=self.return_audio)
text = self.processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)
text = text[0].split("\nassistant\n")[-1]
return text
def invoke(self, messages = list[AnyMessage], file_path: str | None = None) -> AIMessage:
file_type = None
if file_path is not None:
if file_path.endswith(".wav") or file_path.endswith(".mp3"):
file_type = "audio"
elif file_path.endswith(".mp4") or file_path.endswith(".avi"):
file_type = "video"
elif file_path.endswith(".jpg") or file_path.endswith(".png"):
file_type = "image"
else:
raise ValueError("Unsupported file type. Supported types are: .wav, .mp3, .mp4, .avi, .jpg, .png")
parsed_messages = self.__parse_messages(messages, file_path=file_path, file_type=file_type)
response = self.inference(messages=parsed_messages, file_path=file_path, file_type=file_type)
return AIMessage(content=response)
|