Spaces:
Sleeping
Sleeping
Download langgraph_agent.py from juancitro/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 5.14 kB
-
https://huggingface.co/spaces/juancitro/Final_Assignment_Template/resolve/main/langgraph_agent.py
- Command line
-
hf download hf://spaces/juancitro/Final_Assignment_Template/langgraph_agent.py
-
curl -L -o langgraph_agent.py https://huggingface.co/spaces/juancitro/Final_Assignment_Template/resolve/main/langgraph_agent.py
5.14 kB
| 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) | |