Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
| 5 |
import torch.nn.functional as FU
|
| 6 |
from torchvision import transforms
|
| 7 |
import numpy as np
|
| 8 |
from ultralytics import YOLO
|
| 9 |
-
from
|
|
|
|
|
|
|
| 10 |
import torch
|
| 11 |
from pypinyin import pinyin
|
| 12 |
from PIL import Image, ImageDraw, ImageEnhance
|
|
@@ -263,20 +264,21 @@ test_transforms = transforms.Compose([
|
|
| 263 |
|
| 264 |
|
| 265 |
"""import llm from huggingface"""
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
model_name,
|
| 272 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 273 |
-
device_map="auto" if torch.cuda.is_available() else None,
|
| 274 |
-
trust_remote_code=True
|
| 275 |
)
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
"""app functions"""
|
| 282 |
def convert_to_pil(inputimg):
|
|
@@ -436,10 +438,11 @@ def generate_translation(prompt, max_new_tokens=512):
|
|
| 436 |
response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
|
| 437 |
return response.strip()
|
| 438 |
|
| 439 |
-
|
| 440 |
def translate_text(threshhold_slider, is_vertical, input_img):
|
| 441 |
# convert input to pil image
|
| 442 |
pil_img = convert_to_pil(input_img)
|
|
|
|
| 443 |
if pil_img is None:
|
| 444 |
return "", "", ""
|
| 445 |
|
|
@@ -449,16 +452,16 @@ def translate_text(threshhold_slider, is_vertical, input_img):
|
|
| 449 |
chinese_text = ""
|
| 450 |
for crop in sorted_cropped_images:
|
| 451 |
crop = test_transforms(crop)
|
| 452 |
-
crop = crop.to(user_device)
|
| 453 |
-
crop_batch = crop.unsqueeze(dim=0)
|
| 454 |
-
|
| 455 |
classifier.to(user_device)
|
| 456 |
|
| 457 |
logits = classifier(crop_batch)
|
| 458 |
class_idx = logits.argmax(dim=1)
|
| 459 |
|
| 460 |
-
class_idx_cpu = class_idx.cpu().item()
|
| 461 |
-
chinese_charcter = classes_dict[class_idx_cpu]
|
| 462 |
chinese_text += chinese_charcter
|
| 463 |
|
| 464 |
pinyin_text = pinyin(chinese_text)
|
|
@@ -466,24 +469,34 @@ def translate_text(threshhold_slider, is_vertical, input_img):
|
|
| 466 |
for pin in pinyin_text:
|
| 467 |
pinyin_sentence += f"{pin[0]} "
|
| 468 |
|
| 469 |
-
# Enhanced prompt for better translation quality
|
| 470 |
-
prompt = f"""You are a professional Chinese to English translator.
|
| 471 |
-
1. Translate the following Chinese text to natural, fluent English:
|
| 472 |
-
"{chinese_text}"
|
| 473 |
-
2. Respond only with the translated English text.
|
| 474 |
-
English translation: """
|
| 475 |
|
| 476 |
-
|
| 477 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
|
| 479 |
-
#
|
|
|
|
| 480 |
try:
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
except:
|
| 486 |
-
pass
|
| 487 |
|
| 488 |
return chinese_text, pinyin_sentence, translation
|
| 489 |
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
| 4 |
import torch.nn.functional as FU
|
| 5 |
from torchvision import transforms
|
| 6 |
import numpy as np
|
| 7 |
from ultralytics import YOLO
|
| 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
from llama_cpp import Llama
|
| 10 |
+
import os
|
| 11 |
import torch
|
| 12 |
from pypinyin import pinyin
|
| 13 |
from PIL import Image, ImageDraw, ImageEnhance
|
|
|
|
| 264 |
|
| 265 |
|
| 266 |
"""import llm from huggingface"""
|
| 267 |
+
model_path = hf_hub_download(
|
| 268 |
+
repo_id="IncreasingLoss/FineTunedTranslation_Yi-1.5-9B-Chat-Q6_K",
|
| 269 |
+
filename="Yi-1.5-9B-Chat-Q6_K.gguf",
|
| 270 |
+
local_dir="./models", # Optional: specify where to save
|
| 271 |
+
local_dir_use_symlinks=False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
)
|
| 273 |
|
| 274 |
+
print(f"Model downloaded to: {model_path}")
|
| 275 |
+
|
| 276 |
+
llm = Llama(
|
| 277 |
+
model_path=model_path,
|
| 278 |
+
n_ctx=4096,
|
| 279 |
+
n_gpu_layers=-1, # Use all GPU layers
|
| 280 |
+
verbose=False
|
| 281 |
+
)
|
| 282 |
|
| 283 |
"""app functions"""
|
| 284 |
def convert_to_pil(inputimg):
|
|
|
|
| 438 |
response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
|
| 439 |
return response.strip()
|
| 440 |
|
| 441 |
+
|
| 442 |
def translate_text(threshhold_slider, is_vertical, input_img):
|
| 443 |
# convert input to pil image
|
| 444 |
pil_img = convert_to_pil(input_img)
|
| 445 |
+
# FIX #2: Add null check for pil_img
|
| 446 |
if pil_img is None:
|
| 447 |
return "", "", ""
|
| 448 |
|
|
|
|
| 452 |
chinese_text = ""
|
| 453 |
for crop in sorted_cropped_images:
|
| 454 |
crop = test_transforms(crop)
|
| 455 |
+
crop = crop.to(user_device) # Move tensor to device
|
| 456 |
+
crop_batch = crop.unsqueeze(dim=0) # Add batch dimension
|
| 457 |
+
|
| 458 |
classifier.to(user_device)
|
| 459 |
|
| 460 |
logits = classifier(crop_batch)
|
| 461 |
class_idx = logits.argmax(dim=1)
|
| 462 |
|
| 463 |
+
class_idx_cpu = class_idx.cpu().item() # Convert to CPU integer
|
| 464 |
+
chinese_charcter = classes_dict[class_idx_cpu] # Use integer index for list
|
| 465 |
chinese_text += chinese_charcter
|
| 466 |
|
| 467 |
pinyin_text = pinyin(chinese_text)
|
|
|
|
| 469 |
for pin in pinyin_text:
|
| 470 |
pinyin_sentence += f"{pin[0]} "
|
| 471 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
|
| 473 |
+
prompt = f""" You are a professional Chinese to English translator.
|
| 474 |
+
1. Translate the following Chinese text to natural, fluent English:
|
| 475 |
+
"{chinese_text}"
|
| 476 |
+
2. Respond only with the translated English text.
|
| 477 |
+
English translation: """
|
| 478 |
+
|
| 479 |
+
output = llm(
|
| 480 |
+
prompt,
|
| 481 |
+
max_tokens=min(len(chinese_text)*2, 512), # More reasonable token limit with safety cap
|
| 482 |
+
stop=["</s>", "\n\n", "Chinese:", "Chinese text:"], # Enhanced stop tokens
|
| 483 |
+
echo=False,
|
| 484 |
+
temperature=0.3, # Slightly higher temperature for more natural language
|
| 485 |
+
frequency_penalty=.5, # Penalize repetition of tokens - higher values discourage repetition
|
| 486 |
+
presence_penalty=.5, # Penalize tokens that have appeared at all - prevents topic repetition
|
| 487 |
+
top_p=0.9, # Nucleus sampling - restricts to top 90% most likely tokens for more coherent output
|
| 488 |
+
stream=False # Explicitly disable streaming to get a dict response
|
| 489 |
+
)
|
| 490 |
|
| 491 |
+
# Extract the translation
|
| 492 |
+
translation = output["choices"][0]["text"].strip()
|
| 493 |
try:
|
| 494 |
+
start = translation.index('"') + 1
|
| 495 |
+
# find index of last double-quote
|
| 496 |
+
end = translation.rindex('"')
|
| 497 |
+
translation = translation[start:end]
|
| 498 |
except:
|
| 499 |
+
pass
|
| 500 |
|
| 501 |
return chinese_text, pinyin_sentence, translation
|
| 502 |
|