Update app.py
Browse files4 unmodified lines567889101112248 unmodified lines261262263263264265266267268264265266267268269270271272273274275276277278279280281126 unmodified lines4084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414064424434443 unmodified lines4484494504164174184514524534544554564574584244254594604614624631 unmodified line4654664674684694704714724734744344354364374384394404414424434444454464474484494504754764774524534784794554564574584804814824834844604854864874884 unmodified linesfrom torchvision import transformsimport numpy as np from ultralytics import YOLOfrom llama_cpp import Llamafrom transformers import AutoTokenizer, AutoModelForCausalLMimport torchfrom 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 size n_gpu_layers=-1, # -1 means use all available GPU layers verbose=False # Set to True for debugging information"""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 lines selected_index = evt.index return example_images[selected_index]
def generate_translation(prompt, max_new_tokens=512): """Generate translation using Hugging Face model""" # Tokenize input inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=4096-max_new_tokens) # Move to same device as model inputs = {k: v.to(hf_model.device) for k, v in inputs.items()} # Generate response with 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 image pil_img = convert_to_pil(input_img) # FIX #2: Add null check for pil_img if pil_img is None: return "", "", ""
3 unmodified lines chinese_text = "" for crop in sorted_cropped_images: crop = test_transforms(crop) crop = crop.to(user_device) # Move tensor to device crop_batch = crop.unsqueeze(dim=0) # Add batch dimension
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() # Convert to CPU integer chinese_charcter = classes_dict[class_idx_cpu] # Use integer index for list class_idx_cpu = class_idx.cpu().item() chinese_charcter = classes_dict[class_idx_cpu] chinese_text += chinese_charcter
pinyin_text = pinyin(chinese_text)1 unmodified line for pin in pinyin_text: pinyin_sentence += f"{pin[0]} "
# Enhanced prompt for better translation quality 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: """
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 cap stop=["</s>", "\n\n", "Chinese:", "Chinese text:"], # Enhanced stop tokens echo=False, temperature=0.3, # Slightly higher temperature for more natural language frequency_penalty=.5, # Penalize repetition of tokens - higher values discourage repetition presence_penalty=.5, # Penalize tokens that have appeared at all - prevents topic repetition top_p=0.9, # Nucleus sampling - restricts to top 90% most likely tokens for more coherent output stream=False # Explicitly disable streaming to get a dict response ) # Use Hugging Face model instead of llama_cpp translation = generate_translation(prompt, max_new_tokens=min(len(chinese_text)*2, 512)) # Extract the translation translation = output["choices"][0]["text"].strip() # Clean up the translation try: start = translation.index('"') + 1 # find index of last double-quote end = translation.rindex('"') translation = translation[start:end] if '"' in translation: start = translation.index('"') + 1 end = translation.rindex('"') translation = translation[start:end] except: pass pass
return chinese_text, pinyin_sentence, translation
app.py+62-37