Update app.py
Browse files12345672 unmodified lines1011121314156 unmodified lines22232425262728165 unmodified lines19419519619719819920022 unmodified lines22322422522622722822923023123223325 unmodified lines25926026126226326426526626726826927027168 unmodified lines34034134234334434534639 unmodified lines3863873883893903918 unmodified lines4004014024034044057 unmodified lines4134144154164174184196 unmodified lines4264274284294304314322 unmodified lines43543643743843944044128 unmodified lines470471472473474475476import gradio as grimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision import transformsimport numpy as npfrom ultralytics import YOLO2 unmodified linesfrom PIL import Image, ImageDraw, ImageEnhanceimport jsonimport os"""yolo model"""user_device = "cuda" if torch.cuda.is_available() else "cpu"6 unmodified linesclass HSwish(nn.Module):"""Hard Swish activation function"""def forward(self, x):out = x * F.relu6(x + 3, inplace=True) / 6return outclass MV2_Block(nn.Module):165 unmodified linesclassifier.to(user_device).eval()"""load classes dict"""with open("model/LW_Vit/chinese_classes.json", "r", encoding="utf-8") as f:classes_dict = json.load(f)"""transforms"""22 unmodified linespad_w_extra = (max_dim - w) % 2pad_h_extra = (max_dim - h) % 2# Create padding tuple (left, top, right, bottom)padding = (pad_w, pad_h, pad_w + pad_w_extra, pad_h + pad_h_extra)# Create new padded imagepadded_img = transforms.functional.pad(img, padding, fill=self.fill)return padded_img25 unmodified lines"""import llm"""llm = Llama.from_pretrained(repo_id="IncreasingLoss/FineTunedTranslation_Yi-1.5-9B-Chat-Q6_K",filename="*.gguf",n_ctx=4096,n_gpu_layers=-1,verbose=False)"""app functions"""def convert_to_pil(inputimg):# convert input to pil image68 unmodified linesfor idx in order[1:]:c = coords[idx]# if within threshold of this cluster’s mean, add; else start newif abs(c - current_mean) <= threshold:current.append(idx)# update cluster mean incrementally39 unmodified linesdef move_slider(threshhold_slider, input_img):pil_img = convert_to_pil(input_img)with torch.inference_mode():results = detection_model(source=pil_img, conf=threshhold_slider)draw_img = draw_bboxes(pil_img, results)8 unmodified linesdef translate_text(threshhold_slider, is_vertical, input_img):# convert input to pil imagepil_img = convert_to_pil(input_img)with torch.inference_mode():results = detection_model(source=pil_img, conf=threshhold_slider)7 unmodified lineschinese_charcter = classes_dict[class_idx]chinese_text += chinese_charcter#chinese_text = "这是一句测试语句,用来检验我的深度翻译计算机语言模型。"pinyin_text = pinyin(chinese_text)pinyin_sentence = " "for pin in pinyin_text:6 unmodified lines2. Respond only with the translated English text.English translation: """#try:output = llm(prompt,max_tokens=min(len(chinese_text)*2, 512), # More reasonable token limit with safety cap2 unmodified linestemperature=0.3, # Slightly higher temperature for more natural languagefrequency_penalty=.5, # Penalize repetition of tokens - higher values discourage repetitionpresence_penalty=.5, # Penalize tokens that have appeared at all - prevents topic repetitiontop_p=0.9 # Nucleus sampling - restricts to top 90% most likely tokens for more coherent output)# Extract the translation28 unmodified linesmax-height: none !important; /* cancel the global max-height */height: auto !important; /* allow auto height */}/* 2) Same-query override: mirror Gradio’s media query exactly */@media (min-width: 1280px) {/* target the exact same class chain inside the breakpoint */.fixed-height.svelte-842rpi.svelte-842rpi {12345672 unmodified lines10111213141516176 unmodified lines24252627282930165 unmodified lines19619719819920020120222 unmodified lines22522622722822923023123223323423525 unmodified lines26126226326426526626726826927027127268 unmodified lines34134234334434534634739 unmodified lines3873883893903913923933943958 unmodified lines4044054064074084094104114127 unmodified lines4204214224234244256 unmodified lines4324334344354364374382 unmodified lines44144244344444544644744828 unmodified lines477478479480481482483import gradio as grimport torchimport torch.nn as nnimport torch.nn.functional as FUfrom torchvision import transformsimport numpy as npfrom ultralytics import YOLO2 unmodified linesfrom PIL import Image, ImageDraw, ImageEnhanceimport jsonimport osimport torchvision.transforms.functional as F"""yolo model"""user_device = "cuda" if torch.cuda.is_available() else "cpu"6 unmodified linesclass HSwish(nn.Module):"""Hard Swish activation function"""def forward(self, x):out = x * FU.relu6(x + 3, inplace=True) / 6return outclass MV2_Block(nn.Module):165 unmodified linesclassifier.to(user_device).eval()"""load classes dict"""with open("model/chinese_classes.json", "r", encoding="utf-8") as f:classes_dict = json.load(f)"""transforms"""22 unmodified linespad_w_extra = (max_dim - w) % 2pad_h_extra = (max_dim - h) % 2# Create padding list (left, top, right, bottom) - FIX #1: Use list instead of tuplepadding = [pad_w, pad_h, pad_w + pad_w_extra, pad_h + pad_h_extra]# Create new padded imagepadded_img = F.pad(img, padding, self.fill)return padded_img25 unmodified lines"""import llm"""llm = Llama.from_pretrained(repo_id="IncreasingLoss/FineTunedTranslation_Yi-1.5-9B-Chat-Q6_K",filename="*.gguf", # or specify exact file name if only one GGUF in repon_ctx=4096,n_gpu_layers=-1,verbose=False)"""app functions"""def convert_to_pil(inputimg):# convert input to pil image68 unmodified linesfor idx in order[1:]:c = coords[idx]# if within threshold of this cluster's mean, add; else start newif abs(c - current_mean) <= threshold:current.append(idx)# update cluster mean incrementally39 unmodified linesdef move_slider(threshhold_slider, input_img):pil_img = convert_to_pil(input_img)# FIX #2: Add null check for pil_imgif pil_img is None:return Nonewith torch.inference_mode():results = detection_model(source=pil_img, conf=threshhold_slider)draw_img = draw_bboxes(pil_img, results)8 unmodified linesdef translate_text(threshhold_slider, is_vertical, input_img):# convert input to pil imagepil_img = convert_to_pil(input_img)# FIX #2: Add null check for pil_imgif pil_img is None:return "", "", ""with torch.inference_mode():results = detection_model(source=pil_img, conf=threshhold_slider)7 unmodified lineschinese_charcter = classes_dict[class_idx]chinese_text += chinese_charcterpinyin_text = pinyin(chinese_text)pinyin_sentence = " "for pin in pinyin_text:6 unmodified lines2. Respond only with the translated English text.English translation: """# FIX #3: Disable streaming to get direct dict accessoutput = llm(prompt,max_tokens=min(len(chinese_text)*2, 512), # More reasonable token limit with safety cap2 unmodified linestemperature=0.3, # Slightly higher temperature for more natural languagefrequency_penalty=.5, # Penalize repetition of tokens - higher values discourage repetitionpresence_penalty=.5, # Penalize tokens that have appeared at all - prevents topic repetitiontop_p=0.9, # Nucleus sampling - restricts to top 90% most likely tokens for more coherent outputstream=False # Explicitly disable streaming to get a dict response)# Extract the translation28 unmodified linesmax-height: none !important; /* cancel the global max-height */height: auto !important; /* allow auto height */}/* 2) Same-query override: mirror Gradio's media query exactly */@media (min-width: 1280px) {/* target the exact same class chain inside the breakpoint */.fixed-height.svelte-842rpi.svelte-842rpi {
app.py+20-13