Spaces:
Build error
Build error
Add media validation, improve code readability, and fix bugs
Browse files- Implement media input validation logic (image count limits, prohibit mixing videos and images)
- Reorganize code structure to improve readability
- Fix bug where user message was ignored when processing video input
123457 unmodified lines13141516171819202122232416 unmodified lines414243444546474849505152535455565758596061626364656667686970717273747576777879808182838420 unmodified lines105106107108109110#!/usr/bin/env pythonimport reimport tempfilefrom collections.abc import Iterator7 unmodified linesfrom PIL import Imagefrom transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIteratorStreamermodel_id = "google/gemma-3-12b-it"processor = AutoProcessor.from_pretrained(model_id, padding_side="left")model = Gemma3ForConditionalGeneration.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, attn_implementation="eager")def downsample_video(video_path: str) -> list[tuple[Image.Image, float]]:vidcap = cv2.VideoCapture(video_path)16 unmodified linesreturn framesdef process_new_user_message(message: dict) -> list[dict]:if not message["files"]:return [{"type": "text", "text": message["text"]}]if len([path for path in message["files"] if path.endswith(".mp4")]) > 1:raise gr.Error("Only one video is supported at a time.")if "<image>" in message["text"]:content = []logger.debug(f"{message['files']=}")parts = re.split(r"(<image>)", message["text"])image_index = 0logger.debug(f"{parts=}")for part in parts:logger.debug(f"{part=}")if part == "<image>":content.append({"type": "image", "url": message["files"][image_index]})logger.debug(f"file: {message['files'][image_index]}")image_index += 1elif part.strip():content.append({"type": "text", "text": part.strip()})elif isinstance(part, str) and part != "<image>":content.append({"type": "text", "text": part})logger.debug(f"{content=}")return contentif message["files"][0].endswith(".mp4"):content = []video = message["files"].pop(0)frames = downsample_video(video)for frame in frames:pil_image, timestamp = framewith tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:pil_image.save(temp_file.name)content.append({"type": "text", "text": f"Frame {timestamp}:"})content.append({"type": "image", "url": temp_file.name})logger.debug(f"{content=}")return content# non interleaved imagesreturn [{"type": "text", "text": message["text"]},*[{"type": "image", "url": path} for path in message["files"]],20 unmodified lines@spaces.GPU(duration=120)def run(message: dict, history: list[dict], system_prompt: str = "", max_new_tokens: int = 512) -> Iterator[str]:messages = []if system_prompt:messages.append({"role": "system", "content": [{"type": "text", "text": system_prompt}]})1234567 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757616 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114220 unmodified lines163164165166167168169170171172#!/usr/bin/env pythonimport osimport reimport tempfilefrom collections.abc import Iterator7 unmodified linesfrom PIL import Imagefrom transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIteratorStreamermodel_id = os.getenv("MODEL_ID", "google/gemma-3-12b-it")processor = AutoProcessor.from_pretrained(model_id, padding_side="left")model = Gemma3ForConditionalGeneration.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, attn_implementation="eager")MAX_NUM_IMAGES = int(os.getenv("MAX_NUM_IMAGES", "5"))def count_files_in_new_message(paths: list[str]) -> tuple[int, int]:image_count = 0video_count = 0for path in paths:if path.endswith(".mp4"):video_count += 1else:image_count += 1return image_count, video_countdef count_files_in_history(history: list[dict]) -> tuple[int, int]:image_count = 0video_count = 0for item in history:if item["role"] != "user" or isinstance(item["content"], str):continueif item["content"][0].endswith(".mp4"):video_count += 1else:image_count += 1return image_count, video_countdef validate_media_constraints(message: dict, history: list[dict]) -> bool:new_image_count, new_video_count = count_files_in_new_message(message["files"])history_image_count, history_video_count = count_files_in_history(history)image_count = history_image_count + new_image_countvideo_count = history_video_count + new_video_countif video_count > 1:gr.Warning("Only one video is supported.")return Falseif video_count == 1:if image_count > 0:gr.Warning("Mixing images and videos is not allowed.")return Falseif "<image>" in message["text"]:gr.Warning("Using <image> tags with video files is not supported.")return False# TODO: Add frame count validation for videos similar to image count limits # noqa: FIX002, TD002, TD003if video_count == 0 and image_count > MAX_NUM_IMAGES:gr.Warning(f"You can upload up to {MAX_NUM_IMAGES} images.")return Falseif "<image>" in message["text"] and message["text"].count("<image>") != new_image_count:gr.Warning("The number of <image> tags in the text does not match the number of images.")return Falsereturn Truedef downsample_video(video_path: str) -> list[tuple[Image.Image, float]]:vidcap = cv2.VideoCapture(video_path)16 unmodified linesreturn framesdef process_video(video_path: str) -> list[dict]:content = []frames = downsample_video(video_path)for frame in frames:pil_image, timestamp = framewith tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:pil_image.save(temp_file.name)content.append({"type": "text", "text": f"Frame {timestamp}:"})content.append({"type": "image", "url": temp_file.name})logger.debug(f"{content=}")return contentdef process_interleaved_images(message: dict) -> list[dict]:logger.debug(f"{message['files']=}")parts = re.split(r"(<image>)", message["text"])logger.debug(f"{parts=}")content = []image_index = 0for part in parts:logger.debug(f"{part=}")if part == "<image>":content.append({"type": "image", "url": message["files"][image_index]})logger.debug(f"file: {message['files'][image_index]}")image_index += 1elif part.strip():content.append({"type": "text", "text": part.strip()})elif isinstance(part, str) and part != "<image>":content.append({"type": "text", "text": part})logger.debug(f"{content=}")return contentdef process_new_user_message(message: dict) -> list[dict]:if not message["files"]:return [{"type": "text", "text": message["text"]}]if message["files"][0].endswith(".mp4"):return [{"type": "text", "text": message["text"]}, *process_video(message["files"][0])]if "<image>" in message["text"]:return process_interleaved_images(message)return [{"type": "text", "text": message["text"]},*[{"type": "image", "url": path} for path in message["files"]],20 unmodified lines@spaces.GPU(duration=120)def run(message: dict, history: list[dict], system_prompt: str = "", max_new_tokens: int = 512) -> Iterator[str]:if not validate_media_constraints(message, history):yield ""returnmessages = []if system_prompt:messages.append({"role": "system", "content": [{"type": "text", "text": system_prompt}]})
app.py+95-33