Spaces:
Running
Running
Download src/inference.py from caizz/nextgpt-v0-source: direct link, hf CLI and curl.
- Browser
- Download file 6.37 kB
-
https://huggingface.co/spaces/caizz/nextgpt-v0-source/resolve/main/src/inference.py
- Command line
-
hf download hf://spaces/caizz/nextgpt-v0-source/src/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/caizz/nextgpt-v0-source/resolve/main/src/inference.py
6.37 kB
| """Small inference adapter around the released NExT-GPT 7b_tiva_v0 code.""" | |
| from __future__ import annotations | |
| import re | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| from model_bundle import resolve_paths | |
| ROOT = Path(__file__).resolve().parent | |
| VENDOR = ROOT / "vendor" | |
| def load_model(): | |
| import torch | |
| import yaml | |
| paths = resolve_paths() | |
| # The legacy pytorchvideo import uses a name removed from torchvision 0.23. | |
| import torchvision.transforms._functional_tensor as tensor_functions | |
| sys.modules.setdefault("torchvision.transforms.functional_tensor", tensor_functions) | |
| sys.path.insert(0, str(VENDOR)) | |
| from model.anyToImageVideoAudio import NextGPTModel | |
| from model.custom_ad import AudioLDMPipeline | |
| from model.custom_sd import StableDiffusionPipeline | |
| from model.custom_vd import TextToVideoSDPipeline | |
| config = yaml.safe_load((VENDOR / "config" / "base.yaml").read_text()) | |
| config.update(yaml.safe_load((VENDOR / "config" / "stage_3.yaml").read_text())) | |
| config.update( | |
| stage=3, mode="test", model="nextgpt", max_length=256, | |
| inference=True, device=torch.device("cuda"), | |
| vicuna_dir=str(paths["vicuna_dir"]), | |
| imagebind_dir=str(paths["imagebind_dir"]), | |
| image_diffusion=str(paths["image_diffusion_dir"]), | |
| audio_diffusion=str(paths["audio_diffusion_dir"]), | |
| video_diffusion=str(paths["video_diffusion_dir"]), | |
| ) | |
| model = NextGPTModel(**config) | |
| checkpoint = torch.load(paths["delta_path"], map_location="cpu", weights_only=True) | |
| load_result = model.load_state_dict(checkpoint, strict=False) | |
| essential = ("llama_proj.", "gen_text_hidden_fcs.", | |
| "gen_text_hidden_fcs_video.", "gen_text_hidden_fcs_audio.") | |
| if load_result.unexpected_keys or any( | |
| key.startswith(essential) or "lora_" in key for key in load_result.missing_keys | |
| ): | |
| raise RuntimeError("NExT-GPT adaptation checkpoint is incomplete or incompatible") | |
| del checkpoint | |
| model = model.eval().half().to("cuda") | |
| pipelines = {} | |
| for name, cls, path in ( | |
| ("image", StableDiffusionPipeline, paths["image_diffusion_dir"]), | |
| ("audio", AudioLDMPipeline, paths["audio_diffusion_dir"]), | |
| ("video", TextToVideoSDPipeline, paths["video_diffusion_dir"]), | |
| ): | |
| pipe = cls.from_pretrained(str(path), torch_dtype=torch.float16, | |
| local_files_only=True).to("cuda") | |
| pipelines[name] = pipe | |
| model.generation_pipelines = pipelines | |
| return model | |
| def _clean_text(text: str) -> str: | |
| text = re.sub(r"\[(?:IMG|VID|AUD)\d+\]", "", text) | |
| text = re.sub(r"\n?###(?:\s*(?:Assistant|Human):)?", "", text) | |
| return text.strip() | |
| def infer(model, prompt: str, image_path: str | None, audio_path: str | None, | |
| video_path: str | None, temperature: float = 0.4, | |
| max_tokens: int = 128) -> tuple[str, str | None, str | None, str | None]: | |
| import scipy.io.wavfile | |
| import torch | |
| import imageio.v2 as imageio | |
| prompt = (prompt or "").strip() | |
| if not prompt and not any((image_path, audio_path, video_path)): | |
| raise ValueError("请输入文本,或上传一种输入媒体。") | |
| if not 0 < temperature <= 2 or not 1 <= max_tokens <= 256: | |
| raise ValueError("生成参数超出范围。") | |
| if any(x in prompt for x in ("<Image>", "<Audio>", "<Video>")): | |
| raise ValueError("请用上传控件提供媒体,不要在文字中写文件标记。") | |
| segments = ["### Human:"] | |
| for label, path in (("Image", image_path), ("Audio", audio_path), ("Video", video_path)): | |
| if path: | |
| real_path = Path(path).resolve() | |
| if not real_path.is_file() or any(c in str(real_path) for c in "<>\r\n"): | |
| raise ValueError(f"无效的{label}输入文件。") | |
| segments.append(f"<{label}>{real_path}</{label}>") | |
| segments.append(prompt or "请描述输入内容。") | |
| with torch.inference_mode(): | |
| outputs = model.generate({ | |
| "prompt": " ".join(segments), | |
| "image_paths": [image_path] if image_path else [], | |
| "audio_paths": [audio_path] if audio_path else [], | |
| "video_paths": [video_path] if video_path else [], | |
| "top_p": 1.0, "temperature": float(temperature), | |
| "max_tgt_len": int(max_tokens), "modality_embeds": None, | |
| "filter_value": -float("inf"), "min_word_tokens": 10, | |
| "gen_scale_factor": 4.0, "max_num_imgs": 1, | |
| "max_num_vids": 1, "max_num_auds": 1, | |
| "stops_id": [[835]], "load_sd": True, | |
| "generator": torch.Generator(device="cuda").manual_seed(13), | |
| "guidance_scale_for_img": 7.5, "num_inference_steps_for_img": 20, | |
| "guidance_scale_for_vid": 7.5, "num_inference_steps_for_vid": 12, | |
| "height": 320, "width": 576, "num_frames": 8, | |
| "guidance_scale_for_aud": 7.5, "num_inference_steps_for_aud": 20, | |
| "audio_length_in_s": 5.0, "ENCOUNTERS": 1, | |
| }) | |
| text_parts, image_out, video_out, audio_out = [], None, None, None | |
| output_dir = Path(tempfile.mkdtemp(prefix="nextgpt-")) | |
| for item in outputs: | |
| if isinstance(item, str): | |
| text_parts.append(item) | |
| continue | |
| if not isinstance(item, dict): | |
| raise TypeError(f"Unexpected model output: {type(item).__name__}") | |
| for value in item.get("img", []): | |
| if isinstance(value, str): | |
| text_parts.append(value) | |
| else: | |
| image_out = str(output_dir / "image.png") | |
| value[0].save(image_out) | |
| for value in item.get("vid", []): | |
| if isinstance(value, str): | |
| text_parts.append(value) | |
| else: | |
| video_out = str(output_dir / "video.mp4") | |
| imageio.mimwrite(video_out, value, fps=8, codec="libx264", | |
| pixelformat="yuv420p", output_params=["-movflags", "+faststart"]) | |
| for value in item.get("aud", []): | |
| if isinstance(value, str): | |
| text_parts.append(value) | |
| else: | |
| audio_out = str(output_dir / "audio.wav") | |
| scipy.io.wavfile.write(audio_out, rate=16000, data=value) | |
| return _clean_text("\n".join(text_parts)), image_out, video_out, audio_out | |