Update app.py
Browse files4 unmodified lines567891011248 unmodified lines260261262263264265266267268269270271272273126 unmodified lines4004014024034044054064074084093 unmodified lines4134144154164174184194204214224234244254264274281 unmodified line4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634 unmodified linesfrom torchvision import transformsimport numpy as npfrom ultralytics import YOLOfrom llama_cpp import Llamafrom pypinyin import pinyinfrom PIL import Image, ImageDraw, ImageEnhanceimport json248 unmodified lines])"""import llm"""llm = Llama(model_path="model/Yi-1.5-9B-Chat-Q6_K.gguf",n_ctx=4096, # Context window sizen_gpu_layers=-1, # -1 means use all available GPU layersverbose=False # Set to True for debugging information)"""app functions"""def convert_to_pil(inputimg):126 unmodified linesselected_index = evt.indexreturn example_images[selected_index]def 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 "", "", ""3 unmodified lineschinese_text = ""for crop in sorted_cropped_images:crop = test_transforms(crop)crop = crop.to(user_device) # Move tensor to devicecrop_batch = crop.unsqueeze(dim=0) # Add batch dimensionclassifier.to(user_device)logits = classifier(crop_batch)class_idx = logits.argmax(dim=1)class_idx_cpu = class_idx.cpu().item() # Convert to CPU integerchinese_charcter = classes_dict[class_idx_cpu] # Use integer index for listchinese_text += chinese_charcterpinyin_text = pinyin(chinese_text)1 unmodified linefor pin in pinyin_text:pinyin_sentence += f"{pin[0]} "prompt = f""" You are a professional Chinese to English translator.1. Translate the following Chinese text to natural, fluent English:"{chinese_text}"2. Respond only with the translated English text.English translation: """output = llm(prompt,max_tokens=min(len(chinese_text)*2, 512), # More reasonable token limit with safety capstop=["</s>", "\n\n", "Chinese:", "Chinese text:"], # Enhanced stop tokensecho=False,temperature=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 translationtranslation = output["choices"][0]["text"].strip()try:start = translation.index('"') + 1# find index of last double-quoteend = translation.rindex('"')translation = translation[start:end]except:passreturn chinese_text, pinyin_sentence, translation4 unmodified lines56789101112248 unmodified lines261262263264265266267268269270271272273274275276277278279280281126 unmodified lines4084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434443 unmodified lines4484494504514524534544554564574584594604614624631 unmodified line4654664674684694704714724734744754764774784794804814824834844854864874884 unmodified linesfrom torchvision import transformsimport numpy as npfrom ultralytics import YOLOfrom transformers import AutoTokenizer, AutoModelForCausalLMimport torchfrom pypinyin import pinyinfrom PIL import Image, ImageDraw, ImageEnhanceimport json248 unmodified lines])"""import llm from huggingface"""model_name = "IncreasingLoss/FineTunedTranslation_Yi-1.5-9B-Chat-Q6_K/Yi-1.5-9B-Chat-Q6_K.gguf"# Load tokenizer and modeltokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)hf_model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,device_map="auto" if torch.cuda.is_available() else None,trust_remote_code=True)# Set padding token if not already setif tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_token"""app functions"""def convert_to_pil(inputimg):126 unmodified linesselected_index = evt.indexreturn example_images[selected_index]def generate_translation(prompt, max_new_tokens=512):"""Generate translation using Hugging Face model"""# Tokenize inputinputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=4096-max_new_tokens)# Move to same device as modelinputs = {k: v.to(hf_model.device) for k, v in inputs.items()}# Generate responsewith torch.no_grad():outputs = hf_model.generate(**inputs,max_new_tokens=max_new_tokens,temperature=0.3,do_sample=True,top_p=0.9,repetition_penalty=1.1,pad_token_id=tokenizer.eos_token_id,eos_token_id=tokenizer.eos_token_id,stop_strings=["</s>", "\n\n", "Chinese:", "Chinese text:"],)# Decode only the new tokens (exclude the input prompt)response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)return response.strip()# Updated translate_text functiondef translate_text(threshhold_slider, is_vertical, input_img):# convert input to pil imagepil_img = convert_to_pil(input_img)if pil_img is None:return "", "", ""3 unmodified lineschinese_text = ""for crop in sorted_cropped_images:crop = test_transforms(crop)crop = crop.to(user_device)crop_batch = crop.unsqueeze(dim=0)classifier.to(user_device)logits = classifier(crop_batch)class_idx = logits.argmax(dim=1)class_idx_cpu = class_idx.cpu().item()chinese_charcter = classes_dict[class_idx_cpu]chinese_text += chinese_charcterpinyin_text = pinyin(chinese_text)1 unmodified linefor pin in pinyin_text:pinyin_sentence += f"{pin[0]} "# Enhanced prompt for better translation qualityprompt = f"""You are a professional Chinese to English translator.1. Translate the following Chinese text to natural, fluent English:"{chinese_text}"2. Respond only with the translated English text.English translation: """# Use Hugging Face model instead of llama_cpptranslation = generate_translation(prompt, max_new_tokens=min(len(chinese_text)*2, 512))# Clean up the translationtry:if '"' in translation:start = translation.index('"') + 1end = translation.rindex('"')translation = translation[start:end]except:passreturn chinese_text, pinyin_sentence, translation
app.py+62-37