import argparse
import json
import os
import re
import sys
import tempfile
import zipfile
from copy import deepcopy
from pathlib import Path
import gradio as gr
import imageio
import ipdb
import mdtex2html
import scipy
import spaces
import torch
from huggingface_hub import snapshot_download
from PIL import Image
# Unpack the vendored course implementation for browser-upload deployment.
SPACE_ROOT = Path(__file__).parent
LEGACY_ARCHIVE = SPACE_ROOT / 'nextgpt_legacy.zip'
LEGACY_CODE = SPACE_ROOT / 'nextgpt_legacy'
if not LEGACY_CODE.exists() and LEGACY_ARCHIVE.exists():
with zipfile.ZipFile(LEGACY_ARCHIVE) as archive:
archive.extractall(SPACE_ROOT)
# The legacy imports resolve from the course code folder.
sys.path.insert(0, str(LEGACY_CODE))
os.chdir(LEGACY_CODE)
from config import *
from model.anyToImageVideoAudio import NextGPTModel
from transformers import AutoModel, AutoTokenizer
# init the model
parser = argparse.ArgumentParser(description='train parameters')
parser.add_argument('--model', type=str, default='nextgpt')
parser.add_argument('--nextgpt_ckpt_path', type=str, default='../ckpt/delta_ckpt/nextgpt/7b_tiva_v0')
parser.add_argument('--stage', type=int, default=3)
parser.add_argument('--mode', type=str, default='test')
args = parser.parse_args()
args = vars(args)
args.update(load_config(args))
max_length = args['max_length']
# Download and initialize only on GPU-backed Spaces. This lets the interface
# start on CPU while clearly reporting that inference needs GPU hardware.
model = None
g_cuda = None
if torch.cuda.is_available():
checkpoint_root = Path('../ckpt').resolve()
vicuna_path = checkpoint_root / 'pretrained_ckpt' / 'vicuna_ckpt' / args['vicuna_version']
delta_path = Path(args['nextgpt_ckpt_path']).resolve()
if not (vicuna_path / 'config.json').exists():
snapshot_download('lmsys/vicuna-7b-v1.5', local_dir=str(vicuna_path))
if not (delta_path / 'pytorch_model.pt').exists():
snapshot_download('ChocoWu/nextgpt_7b_tiva_v0', local_dir=str(delta_path))
model = NextGPTModel(**args)
delta_ckpt = torch.load(delta_path / 'pytorch_model.pt', map_location=torch.device('cpu'), weights_only=False)
model.load_state_dict(delta_ckpt, strict=False)
model = model.eval().half().cuda()
print('[!] init the 7b model over ...')
g_cuda = torch.Generator(device='cuda').manual_seed(13)
else:
print('[!] No CUDA device is available. Select GPU hardware in Space settings to enable inference.')
filter_value = -float('Inf')
min_word_tokens = 10
gen_scale_factor = 4.0
stops_id = [[835]]
ENCOUNTERS = 1
load_sd = True
generator = g_cuda
max_num_imgs = 1
max_num_vids = 1
height = 320
width = 576
max_num_auds = 1
max_length = 246
"""Override Chatbot.postprocess"""
def postprocess(self, y):
if y is None:
return []
for i, (message, response) in enumerate(y):
y[i] = (
None if message is None else mdtex2html.convert((message)),
None if response is None else mdtex2html.convert(response),
)
return y
gr.Chatbot.postprocess = postprocess
def parse_text(text, image_path, video_path, audio_path):
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
outputs = text
lines = text.split("\n")
lines = [line for line in lines if line != ""]
count = 0
for i, line in enumerate(lines):
if "```" in line:
count += 1
items = line.split('`')
if count % 2 == 1:
lines[i] = f'
'
else:
lines[i] = f'
'
else:
if i > 0:
if count % 2 == 1:
line = line.replace("`", "\`")
line = line.replace("<", "<")
line = line.replace(">", ">")
line = line.replace(" ", " ")
line = line.replace("*", "*")
line = line.replace("_", "_")
line = line.replace("-", "-")
line = line.replace(".", ".")
line = line.replace("!", "!")
line = line.replace("(", "(")
line = line.replace(")", ")")
line = line.replace("$", "$")
lines[i] = " " + line
text = "".join(lines) + " "
res_text = ''
split_text = re.split(r' <|> ', text)
image_path_list, video_path_list, audio_path_list = [], [], []
for st in split_text:
if st.startswith(''):
pattern = r'Image>(.*?)<\/Image'
matches = re.findall(pattern, text)
for m in matches:
image_path_list.append(m)
elif st.startswith('