Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (2)
- apps/text_tools.py+71-36
- requirements.txt+2-1
3 unmodified lines45678910111213142 unmodified lines1718192021222324252627284 unmodified lines33343536373839404142434445464748492 unmodified lines5253545556575859606162635 unmodified lines6970717273747576777879808122 unmodified lines1041051061071081091101111121131141151161171 unmodified line1191201211221231241251261271282 unmodified lines13113213313413513613713812 unmodified lines1511521531541551561571581591601611621631641651661676 unmodified lines1741751761771781791801811821831841851861871881891902 unmodified lines19319419519619719819922 unmodified lines22222322422522622716 unmodified lines2442452462472482493 unmodified linesimport osfrom transformers import AutoTokenizer# --- Tokenizer 加载逻辑 ---# 为了避免每次请求都重新加载,我们可以尝试缓存 tokenizer# 但在 HF Spaces 中,内存有限,且模型可能很大。# 对于 Qwen2.5-VL,我们可以使用 Qwen/Qwen2.5-VL-7B-Instruct 的 tokenizer# 对于 Llava,通常使用 Llama-2 或 Vicuna 的 tokenizerTOKENIZERS = {}def get_tokenizer(model_name):2 unmodified linestry:if model_name == "Qwen2.5-VL / Qwen2-VL":# Qwen2-VL 使用 Qwen2 的 tokenizer# 注意:这里需要联网下载 tokenizer.json,HF Spaces 通常允许tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", trust_remote_code=True)elif model_name == "Llava-1.6 (Next)":# Llava-1.6 基于 Vicuna/Llama-2,这里用 Llama-2 tokenizer 近似,或者直接用 llava-hf# 为了通用性,我们使用 llava-hf/llava-v1.6-vicuna-7b-hftokenizer = AutoTokenizer.from_pretrained("llava-hf/llava-v1.6-vicuna-7b-hf", trust_remote_code=True)else:return None4 unmodified linesprint(f"Error loading tokenizer for {model_name}: {e}")return None# --- Token 计算逻辑 ---def calculate_qwen2_vl_tokens(text, images, videos, tokenizer):"""Qwen2-VL / Qwen2.5-VL Token 计算公式"""text_tokens_count = 0image_tokens_count = 0video_tokens_count = 0# 1. 文本 Token (真实计算)text_tokens_ids = []if tokenizer:text_tokens_ids = tokenizer.encode(text)2 unmodified lines# Fallbacktext_tokens_count = len(text) // 2# 2. 图片 Tokenimage_details = []for img in images:width, height = img['width'], img['height']new_w = int(round(width / 28.0) * 28)new_h = int(round(height / 28.0) * 28)grid_w = new_w // 14grid_h = new_h // 14img_tokens = grid_h * grid_w5 unmodified lines"tokens": img_tokens})# 3. 视频 Tokenvideo_details = []for vid in videos:frames = vid['frames']width, height = vid['width'], vid['height']new_w = int(round(width / 28.0) * 28)new_h = int(round(height / 28.0) * 28)grid_w = new_w // 14grid_h = new_h // 14frame_tokens = grid_h * grid_w22 unmodified linesreturn total_tokens, text_tokens_ids, breakdown, media_detailsdef calculate_llava_next_tokens(text, images, tokenizer):"""Llava-1.6 (Next) Token 计算公式"""text_tokens_count = 0image_tokens_count = 0# 1. 文本 Tokentext_tokens_ids = []if tokenizer:text_tokens_ids = tokenizer.encode(text)1 unmodified lineelse:text_tokens_count = len(text) // 2# 2. 图片 Tokenimage_details = []for img in images:width, height = img['width'], img['height']scale_res = 336patch_x = math.ceil(width / scale_res)patch_y = math.ceil(height / scale_res)2 unmodified linesimage_tokens_count += img_tokensimage_details.append({"original_size": [width, height],"resized_size": ["Dynamic Grid", f"{patch_x}x{patch_y} patches"],"tokens": img_tokens})12 unmodified linesreturn total_tokens, text_tokens_ids, breakdown, media_details# --- 实际 UI 逻辑 ---def run_calculation(text, model, img_count, img_w, img_h, vid_count, vid_frames, vid_w, vid_h):# 构造虚拟数据images = [{'width': img_w, 'height': img_h} for _ in range(int(img_count))]videos = [{'width': vid_w, 'height': vid_h, 'frames': int(vid_frames)} for _ in range(int(vid_count))]# 获取 Tokenizertokenizer = get_tokenizer(model)# 确定真实模型 IDmodel_id_map = {"Qwen2.5-VL / Qwen2-VL": "Qwen/Qwen2.5-VL-7B-Instruct","Llava-1.6 (Next)": "llava-hf/llava-v1.6-vicuna-7b-hf"6 unmodified linestokens = 0if model == "Qwen2.5-VL / Qwen2-VL":tokens, text_tokens_ids, breakdown, media_details = calculate_qwen2_vl_tokens(text, images, videos, tokenizer)elif model == "Llava-1.6 (Next)":tokens, text_tokens_ids, breakdown, media_details = calculate_llava_next_tokens(text, images, tokenizer)else:tokens = 0# 生成 Token 对应文件token_file_path = Noneif tokenizer and text_tokens_ids:token_data = []# 解码每个 token id 对应的 stringfor tid in text_tokens_ids:token_str = tokenizer.decode([tid])token_data.append({"id": tid, "token": token_str})2 unmodified lineswith open(token_file_path, "w", encoding="utf-8") as f:json.dump({"text": text, "tokens": token_data}, f, ensure_ascii=False, indent=2)# 构造最终返回的 JSONresult = {"model_id": real_model_id,"tokenizer_loaded": tokenizer is not None,22 unmodified linesimg_count = gr.Number(value=1, label="图片数量", precision=0)img_w = gr.Number(value=1024, label="宽 (px)")img_h = gr.Number(value=1024, label="高 (px)")with gr.Accordion("🎥 视频设置 (Videos)", open=False):with gr.Row():16 unmodified linesbtn.click(run_calculation,[text_input, model_select, img_count, img_w, img_h, vid_count, vid_frames, vid_w, vid_h],[out_json, out_file])3 unmodified lines4567891011121314151617181920212223242526272829303132333435362 unmodified lines394041424344454647484 unmodified lines53545556575859606162636465666768692 unmodified lines72737475767778798081828384855 unmodified lines91929394959697989910010110210310410522 unmodified lines1281291301311321331341351361371381391401411 unmodified line1431441451461471481491501511521531541551561571581591602 unmodified lines16316416516616716816917017112 unmodified lines1841851861871881891901911921931941951961971981992006 unmodified lines2072082092102112122132142152162172182192202212222232 unmodified lines22622722822923023123222 unmodified lines25525625725825926026126216 unmodified lines2792802812822832843 unmodified linesimport osfrom transformers import AutoTokenizer# Try to import qwen_vl_utils, otherwise use the built-in official implementation copytry:from qwen_vl_utils.vision_process import smart_resize as qwen_smart_resizeexcept ImportError:# Qwen-VL-Utils official implementation copydef qwen_smart_resize(height, width, factor=28, min_pixels=56 * 56, max_pixels=1280 * 1280):"""Official implementation from qwen_vl_utils.vision_process"""if max(height, width) / min(height, width) > 200:factor = 1 # For extreme aspect ratiosh_bar = round(height / factor) * factorw_bar = round(width / factor) * factorif h_bar * w_bar > max_pixels:beta = math.sqrt((height * width) / max_pixels)h_bar = math.floor(height / beta / factor) * factorw_bar = math.floor(width / beta / factor) * factorelif h_bar * w_bar < min_pixels:beta = math.sqrt(min_pixels / (height * width))h_bar = math.ceil(height * beta / factor) * factorw_bar = math.ceil(width * beta / factor) * factorreturn h_bar, w_bar# --- Tokenizer Loading Logic ---TOKENIZERS = {}def get_tokenizer(model_name):2 unmodified linestry:if model_name == "Qwen2.5-VL / Qwen2-VL":# Qwen2-VL uses Qwen2 tokenizertokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", trust_remote_code=True)elif model_name == "Llava-1.6 (Next)":# Llava-1.6 based on Vicuna/Llama-2tokenizer = AutoTokenizer.from_pretrained("llava-hf/llava-v1.6-vicuna-7b-hf", trust_remote_code=True)else:return None4 unmodified linesprint(f"Error loading tokenizer for {model_name}: {e}")return None# --- Token Calculation Logic ---def calculate_qwen2_vl_tokens(text, images, videos, tokenizer, max_pixels):"""Qwen2-VL / Qwen2.5-VL Token Calculation Formula"""text_tokens_count = 0image_tokens_count = 0video_tokens_count = 0# 1. Text Tokens (Real Calculation)text_tokens_ids = []if tokenizer:text_tokens_ids = tokenizer.encode(text)2 unmodified lines# Fallbacktext_tokens_count = len(text) // 2# 2. Image Tokensimage_details = []for img in images:width, height = img['width'], img['height']# Apply Qwen Official Smart Resizenew_h, new_w = qwen_smart_resize(height, width, factor=28, min_pixels=56*56, max_pixels=max_pixels)grid_w = new_w // 14grid_h = new_h // 14img_tokens = grid_h * grid_w5 unmodified lines"tokens": img_tokens})# 3. Video Tokensvideo_details = []for vid in videos:frames = vid['frames']width, height = vid['width'], vid['height']# Video processing logic is similar to imagesnew_h, new_w = qwen_smart_resize(height, width, factor=28, min_pixels=56*56, max_pixels=max_pixels)grid_w = new_w // 14grid_h = new_h // 14frame_tokens = grid_h * grid_w22 unmodified linesreturn total_tokens, text_tokens_ids, breakdown, media_detailsdef calculate_llava_next_tokens(text, images, tokenizer, max_pixels):"""Llava-1.6 (Next) Token Calculation Formula"""text_tokens_count = 0image_tokens_count = 0# 1. Text Tokenstext_tokens_ids = []if tokenizer:text_tokens_ids = tokenizer.encode(text)1 unmodified lineelse:text_tokens_count = len(text) // 2# 2. Image Tokensimage_details = []for img in images:width, height = img['width'], img['height']# Llava-Next Logic:# If max_pixels is specified, resize firstif max_pixels > 0 and (width * height > max_pixels):scale_factor = math.sqrt(max_pixels / (width * height))width = int(width * scale_factor)height = int(height * scale_factor)scale_res = 336patch_x = math.ceil(width / scale_res)patch_y = math.ceil(height / scale_res)2 unmodified linesimage_tokens_count += img_tokensimage_details.append({"original_size": [img['width'], img['height']],"resized_size": [width, height],"grid_patches": f"{patch_x}x{patch_y}","tokens": img_tokens})12 unmodified linesreturn total_tokens, text_tokens_ids, breakdown, media_details# --- Actual UI Logic ---def run_calculation(text, model, img_count, img_w, img_h, img_max_pixels, vid_count, vid_frames, vid_w, vid_h):# Construct virtual dataimages = [{'width': img_w, 'height': img_h} for _ in range(int(img_count))]videos = [{'width': vid_w, 'height': vid_h, 'frames': int(vid_frames)} for _ in range(int(vid_count))]# Get Tokenizertokenizer = get_tokenizer(model)# Determine real model IDmodel_id_map = {"Qwen2.5-VL / Qwen2-VL": "Qwen/Qwen2.5-VL-7B-Instruct","Llava-1.6 (Next)": "llava-hf/llava-v1.6-vicuna-7b-hf"6 unmodified linestokens = 0if model == "Qwen2.5-VL / Qwen2-VL":tokens, text_tokens_ids, breakdown, media_details = calculate_qwen2_vl_tokens(text, images, videos, tokenizer, img_max_pixels)elif model == "Llava-1.6 (Next)":tokens, text_tokens_ids, breakdown, media_details = calculate_llava_next_tokens(text, images, tokenizer, img_max_pixels)else:tokens = 0# Generate Token Analysis Filetoken_file_path = Noneif tokenizer and text_tokens_ids:token_data = []# Decode each token idfor tid in text_tokens_ids:token_str = tokenizer.decode([tid])token_data.append({"id": tid, "token": token_str})2 unmodified lineswith open(token_file_path, "w", encoding="utf-8") as f:json.dump({"text": text, "tokens": token_data}, f, ensure_ascii=False, indent=2)# Construct final JSON resultresult = {"model_id": real_model_id,"tokenizer_loaded": tokenizer is not None,22 unmodified linesimg_count = gr.Number(value=1, label="图片数量", precision=0)img_w = gr.Number(value=1024, label="宽 (px)")img_h = gr.Number(value=1024, label="高 (px)")with gr.Row():img_max_pixels = gr.Number(value=1280*1280, label="Max Pixels (最大像素限制)", precision=0)with gr.Accordion("🎥 视频设置 (Videos)", open=False):with gr.Row():16 unmodified linesbtn.click(run_calculation,[text_input, model_select, img_count, img_w, img_h, img_max_pixels, vid_count, vid_frames, vid_w, vid_h],[out_json, out_file])
2 unmodified lines34562 unmodified linesimg2pdfhuggingface_hubtransformerstiktoken2 unmodified lines345672 unmodified linesimg2pdfhuggingface_hubtransformerstiktokenqwen-vl-utils
apps/text_tools.py+71-36
requirements.txt+2-1