Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534import gradio as grimport torchimport torch.nn as nnimport torch.nn.functional as FUfrom torchvision import transformsimport numpy as npfrom ultralytics import YOLOfrom llama_cpp import Llamafrom pypinyin import pinyinfrom PIL import Image, ImageDraw, ImageEnhanceimport jsonimport osimport torchvision.transforms.functional as Ffrom statistics import mean"""yolo model"""user_device = "cuda" if torch.cuda.is_available() else "cpu"detection_model = YOLO("model/yolo/yolo_chinese_m.pt").to(user_device).eval()"""LW-Vit Classifier"""class 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):"""MobileNetV2 Inverted Residual Block with h-swish activation"""def __init__(self, in_channels, expand_channels, out_channels, stride):super().__init__()self.stride = strideself.use_res_connect = self.stride == 1 and in_channels == out_channelsself.expand = nn.Sequential(nn.Conv2d(in_channels, expand_channels, kernel_size=1, stride=1, padding=0, bias=False),nn.BatchNorm2d(expand_channels),HSwish())self.depthwise = nn.Sequential(nn.Conv2d(expand_channels, expand_channels, kernel_size=3, stride=stride,padding=1, groups=expand_channels, bias=False),nn.BatchNorm2d(expand_channels),HSwish())self.project = nn.Sequential(nn.Conv2d(expand_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False),nn.BatchNorm2d(out_channels))def forward(self, x):if self.use_res_connect:return x + self.project(self.depthwise(self.expand(x)))else:return self.project(self.depthwise(self.expand(x)))class LW_ViT_Transformer_Block(nn.Module):"""Lightweight Vision Transformer Block"""def __init__(self, in_channels, out_channels, patch_size=2, heads=4, dim=128):super().__init__()self.patch_size = patch_sizeself.in_channels = in_channelsself.out_channels = out_channelsself.dim = dim# Downsampling and channel adjustmentself.downsample = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=1)self.channel_adjust = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1)# Calculate patch dimensionpatch_dim = out_channels * patch_size * patch_size# Add projection layer if neededself.projection = nn.Identity() if patch_dim == dim else nn.Linear(patch_dim, dim)# Transformer componentsself.norm1 = nn.LayerNorm(dim)self.attn = nn.MultiheadAttention(embed_dim=dim, num_heads=heads, batch_first=True)self.norm2 = nn.LayerNorm(dim)self.ffn = nn.Sequential(nn.Linear(dim, dim * 4),nn.GELU(),nn.Linear(dim * 4, dim))# Final processingself.final_conv = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)self.norm_out = nn.BatchNorm2d(out_channels)self.act = HSwish()def forward(self, x):# Initial downsampling and channel adjustmentx = self.downsample(x)x = self.channel_adjust(x)B, C, H, W = x.shape# Convert feature map to patches and embed# Reshape to [B, C, H/P, P, W/P, P]x_reshaped = x.reshape(B, C, H // self.patch_size, self.patch_size,W // self.patch_size, self.patch_size)# Permute to [B, H/P, W/P, C, P, P]x_permuted = x_reshaped.permute(0, 2, 4, 1, 3, 5)# Reshape to [B, H/P * W/P, C * P * P]patches = x_permuted.reshape(B, (H // self.patch_size) * (W // self.patch_size), -1)# Apply projection if neededpatches = self.projection(patches)# Apply transformer operationsnormed_patches = self.norm1(patches)attn_out, _ = self.attn(normed_patches, normed_patches, normed_patches)patches = patches + attn_outnormed_patches = self.norm2(patches)ffn_out = self.ffn(normed_patches)patches = patches + ffn_out# Reshape back to feature map# Reshape to [B, H/P, W/P, C, P, P]x_back = patches.reshape(B, H // self.patch_size, W // self.patch_size,C, self.patch_size, self.patch_size)# Permute to [B, C, H/P, P, W/P, P]x_back = x_back.permute(0, 3, 1, 4, 2, 5)# Reshape to [B, C, H, W]x_out = x_back.reshape(B, C, H, W)# Final processingout = self.final_conv(x_out)out = self.norm_out(out)out = self.act(out)return outclass LW_ViT(nn.Module):"""Lightweight Vision Transformer for Chinese Character Recognition"""def __init__(self, base_channels=16, num_classes=3892):super().__init__()# Stem layerself.stem = nn.Sequential(nn.Conv2d(3, base_channels, 3, stride=2, padding=1, bias=False),nn.BatchNorm2d(base_channels),HSwish())# Feature extraction layersself.features = nn.Sequential(# MV2 blocksMV2_Block(base_channels, 4*base_channels, base_channels, stride=1),MV2_Block(base_channels, 4*base_channels, base_channels, stride=2),MV2_Block(base_channels, 4*base_channels, base_channels, stride=1),MV2_Block(base_channels, 4*base_channels, base_channels, stride=2),# Transformer blockLW_ViT_Transformer_Block(in_channels=base_channels,out_channels=2*base_channels,patch_size=2,heads=4,dim=128),# Final convolutional layernn.Conv2d(2*base_channels, 4*base_channels, kernel_size=1, stride=1),nn.BatchNorm2d(4*base_channels),HSwish())# Global pooling and classifierself.global_pool = nn.AdaptiveAvgPool2d(1)self.dropout = nn.Dropout(0.1) # Added dropout for regularizationself.classifier = nn.Sequential(nn.Linear(4*base_channels, 8*base_channels),nn.BatchNorm1d(8*base_channels),HSwish(),nn.Dropout(0.1), # Added dropout for regularizationnn.Linear(8*base_channels, num_classes))def forward(self, x):x = self.stem(x)x = self.features(x)x = self.global_pool(x)x = torch.flatten(x, 1)x = self.dropout(x)x = self.classifier(x)return xclassifier = LW_ViT()classifier.load_state_dict(torch.load("model/LW_Vit/chinese_Character_Classification_handwritten_LW_ViT.pth", weights_only=True, map_location=user_device))classifier = classifier.to(user_device)classifier.eval()"""load classes dict"""with open("model/LW_Vit/chinese_classes.json", "r", encoding="utf-8") as f:classes_dict = json.load(f)"""transforms"""class ToSquare(object):"""Transform to make images square by padding the shorter dimension"""def __init__(self, fill=0):self.fill = fill # Fill value for padding (0 = black)def __call__(self, img):w, h = img.size# If already square, return as isif w == h:return img# Calculate target size (max dimension)max_dim = max(w, h)# Calculate paddingpad_w = (max_dim - w) // 2pad_h = (max_dim - h) // 2# Handle odd dimensions (extra pixel on one side)pad_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_imgclass ConvertToRGB(object):"""Convert image to RGB mode"""def __call__(self, img):# Convert any image mode to RGB (including RGBA)return img.convert('RGB')class Contrast(object):"""Randomly adjust contrast"""def __init__(self, p=0.3, factor_range=(0.5, 1.5)):self.p = pself.factor_range = factor_rangedef __call__(self, img):enhancer = ImageEnhance.Contrast(img)return enhancer.enhance(1.5)test_transforms = transforms.Compose([ToSquare(fill=255),transforms.Resize(128),ConvertToRGB(),transforms.ToTensor(),transforms.Normalize(mean=[0.5], std=[0.5])])"""import llm"""llm = Llama(model_path="model/llms/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):# convert input to pil imageif inputimg is None:return Noneif isinstance(inputimg, np.ndarray):pil_img = Image.fromarray(inputimg)elif hasattr(inputimg, 'convert'): # Check if it's already a PIL Imagepil_img = inputimgelse:pil_img = Image.fromarray(np.array(inputimg))pil_img = pil_img.convert("RGB")return pil_imgdef draw_bboxes(img, results):# Create a copy of the input image to draw ondraw_img = img.copy()draw = ImageDraw.Draw(draw_img)# Draw bounding boxes for detected objectsfor box in results[0].boxes.xyxy:x1, y1, x2, y2 = map(int, box) # Convert to integersdraw.rectangle([x1, y1, x2, y2], outline=(255, 0, 0), width=2)return draw_imgdef crop_bboxes_by_reading_order(img, bboxes, written_vertical=False):"""Crop and return image regions in proper reading order.For vertical Chinese:- Group into columns by x-coordinate (clusters whose centers are within avg_width/2)- Order columns right-to-left- Within each column, order top-to-bottom by yFor horizontal:- Group into rows by y-coordinate (clusters within avg_height/2)- Order rows top-to-bottom- Within each row, order left-to-right by x"""# 1) If bboxes is a Tensor, convert to Python listif hasattr(bboxes, "tolist"):bboxes = bboxes.tolist()# 2) Single box -> trivial cropif len(bboxes) <= 1:return [img.crop(tuple(map(int, bbox))) for bbox in bboxes]# 3) Compute centers and average glyph sizecenters = [((x1+x2)/2, (y1+y2)/2) for x1,y1,x2,y2 in bboxes]widths = [x2 - x1 for x1,y1,x2,y2 in bboxes]heights = [y2 - y1 for x1,y1,x2,y2 in bboxes]avg_w = mean(widths)avg_h = mean(heights)# 4) Choose clustering axis and thresholdif written_vertical:coords = [c[0] for c in centers] # x-coordsthreshold = avg_w / 2else:coords = [c[1] for c in centers] # y-coordsthreshold = avg_h / 2# 5) Sort glyphs by the clustering axisorder = sorted(range(len(coords)), key=lambda i: coords[i])# 6) Build clustersclusters = []current = [order[0]]current_mean = coords[order[0]]for 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 incrementallycurrent_mean = mean([coords[i] for i in current])else:clusters.append(current)current = [idx]current_mean = cclusters.append(current)# 7) Order clustersif written_vertical:# Chinese vertical: rightmost column firstclusters.sort(key=lambda grp: mean(coords[i] for i in grp),reverse=True)else:# Horizontal: top row firstclusters.sort(key=lambda grp: mean(coords[i] for i in grp))# 8) Within each cluster, sort by the orthogonal axisfinal_indices = []for grp in clusters:if written_vertical:# sort top-to-bottom by ygrp.sort(key=lambda i: centers[i][1])else:# sort left-to-right by xgrp.sort(key=lambda i: centers[i][0])final_indices.extend(grp)# 9) Crop and returncrops = []for i in final_indices:x1, y1, x2, y2 = map(int, bboxes[i])crops.append(img.crop((x1, y1, x2, y2)))return cropsdef 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)return draw_imgdef select_image(evt: gr.SelectData):selected_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 "", "", ""with torch.inference_mode():results = detection_model(source=pil_img, conf=threshhold_slider)sorted_cropped_images = crop_bboxes_by_reading_order(img=pil_img, bboxes=results[0].boxes.xyxy, written_vertical=is_vertical)chinese_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)pinyin_sentence = " "for 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, translationcss = """.centered-examples {margin: 0 auto !important;justify-content: center !important;gap: 8px !important;min-height: 150px !important; /* Added minimum height */}.centered-examples .thumb {height: 100px !important;width: 100px !important;object-fit: cover !important;margin: 5px !important; /* Added margin between thumbs */}/* 1) Global override: remove any forced sizing on .fixed-height anywhere */.fixed-height.svelte-842rpi.svelte-842rpi {min-height: 0 !important; /* cancel the global min-height */max-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 {min-height: 0 !important; /* zero-out the 55vh/min-height there */max-height: none !important; /* remove the viewport-height cap */height: auto !important; /* let content dictate height */}}""""""gradio app"""example_dir = "examples"example_images = [os.path.join(example_dir, f) for f in os.listdir(example_dir)if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]with gr.Blocks(css=css) as program:gr.Markdown("## DeepTranslate: Chinese OCR with translation to english")gr.Markdown("Upload or select an image and move the slider to detect characters.")gr.Markdown("Make sure that the input image is high resolution and not rotated in any way!")#inputswith gr.Column(scale=1):gallery = gr.Gallery(value=example_images,label="Example Images (Click to Select)",columns=6,allow_preview=False,elem_id="my_media_gallery",elem_classes=["centered-examples"])with gr.Row(scale=2):input_img = gr.Image(label="Input Image ")detection_img = gr.Image(label="Detection Image", interactive= False)# slider and buttonwith gr.Column(scale=1):with gr.Row(scale=3):threshhold_slider = gr.Slider(value=0.25, minimum=0, maximum=0.75, label="Detection Threshhold", step = 0.01)translate_button = gr.Button("Translate To English", variant="primary")is_vertical = gr.Checkbox(value=False, label="Vertiacl Chinese Text?", interactive=True)# outputswith gr.Column(scale=1):with gr.Row(scale=3):chinese_text = gr.TextArea(label="Chinese Text", max_lines= 1000, interactive=False)pinyin_text = gr.TextArea(label="Chinese Pinyin", max_lines= 1000, interactive=False)english_text = gr.TextArea(label="English Text", max_lines= 1000, interactive=False)#function, callingthreshhold_slider.change(fn= move_slider, inputs=[threshhold_slider, input_img], outputs=[detection_img])translate_button.click(fn=translate_text, inputs= [threshhold_slider, is_vertical, input_img], outputs=[chinese_text, pinyin_text, english_text])gallery.select(fn=select_image, inputs=None, outputs=input_img)if __name__ == "__main__":program.launch(share=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534import gradio as grimport torchimport torch.nn as nnimport torch.nn.functional as FUfrom torchvision import transformsimport numpy as npfrom ultralytics import YOLOfrom llama_cpp import Llamafrom pypinyin import pinyinfrom PIL import Image, ImageDraw, ImageEnhanceimport jsonimport osimport torchvision.transforms.functional as Ffrom statistics import mean"""yolo model"""user_device = "cuda" if torch.cuda.is_available() else "cpu"detection_model = YOLO("model/yolo_chinese_m.pt").to(user_device).eval()"""LW-Vit Classifier"""class 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):"""MobileNetV2 Inverted Residual Block with h-swish activation"""def __init__(self, in_channels, expand_channels, out_channels, stride):super().__init__()self.stride = strideself.use_res_connect = self.stride == 1 and in_channels == out_channelsself.expand = nn.Sequential(nn.Conv2d(in_channels, expand_channels, kernel_size=1, stride=1, padding=0, bias=False),nn.BatchNorm2d(expand_channels),HSwish())self.depthwise = nn.Sequential(nn.Conv2d(expand_channels, expand_channels, kernel_size=3, stride=stride,padding=1, groups=expand_channels, bias=False),nn.BatchNorm2d(expand_channels),HSwish())self.project = nn.Sequential(nn.Conv2d(expand_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False),nn.BatchNorm2d(out_channels))def forward(self, x):if self.use_res_connect:return x + self.project(self.depthwise(self.expand(x)))else:return self.project(self.depthwise(self.expand(x)))class LW_ViT_Transformer_Block(nn.Module):"""Lightweight Vision Transformer Block"""def __init__(self, in_channels, out_channels, patch_size=2, heads=4, dim=128):super().__init__()self.patch_size = patch_sizeself.in_channels = in_channelsself.out_channels = out_channelsself.dim = dim# Downsampling and channel adjustmentself.downsample = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=1)self.channel_adjust = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1)# Calculate patch dimensionpatch_dim = out_channels * patch_size * patch_size# Add projection layer if neededself.projection = nn.Identity() if patch_dim == dim else nn.Linear(patch_dim, dim)# Transformer componentsself.norm1 = nn.LayerNorm(dim)self.attn = nn.MultiheadAttention(embed_dim=dim, num_heads=heads, batch_first=True)self.norm2 = nn.LayerNorm(dim)self.ffn = nn.Sequential(nn.Linear(dim, dim * 4),nn.GELU(),nn.Linear(dim * 4, dim))# Final processingself.final_conv = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)self.norm_out = nn.BatchNorm2d(out_channels)self.act = HSwish()def forward(self, x):# Initial downsampling and channel adjustmentx = self.downsample(x)x = self.channel_adjust(x)B, C, H, W = x.shape# Convert feature map to patches and embed# Reshape to [B, C, H/P, P, W/P, P]x_reshaped = x.reshape(B, C, H // self.patch_size, self.patch_size,W // self.patch_size, self.patch_size)# Permute to [B, H/P, W/P, C, P, P]x_permuted = x_reshaped.permute(0, 2, 4, 1, 3, 5)# Reshape to [B, H/P * W/P, C * P * P]patches = x_permuted.reshape(B, (H // self.patch_size) * (W // self.patch_size), -1)# Apply projection if neededpatches = self.projection(patches)# Apply transformer operationsnormed_patches = self.norm1(patches)attn_out, _ = self.attn(normed_patches, normed_patches, normed_patches)patches = patches + attn_outnormed_patches = self.norm2(patches)ffn_out = self.ffn(normed_patches)patches = patches + ffn_out# Reshape back to feature map# Reshape to [B, H/P, W/P, C, P, P]x_back = patches.reshape(B, H // self.patch_size, W // self.patch_size,C, self.patch_size, self.patch_size)# Permute to [B, C, H/P, P, W/P, P]x_back = x_back.permute(0, 3, 1, 4, 2, 5)# Reshape to [B, C, H, W]x_out = x_back.reshape(B, C, H, W)# Final processingout = self.final_conv(x_out)out = self.norm_out(out)out = self.act(out)return outclass LW_ViT(nn.Module):"""Lightweight Vision Transformer for Chinese Character Recognition"""def __init__(self, base_channels=16, num_classes=3892):super().__init__()# Stem layerself.stem = nn.Sequential(nn.Conv2d(3, base_channels, 3, stride=2, padding=1, bias=False),nn.BatchNorm2d(base_channels),HSwish())# Feature extraction layersself.features = nn.Sequential(# MV2 blocksMV2_Block(base_channels, 4*base_channels, base_channels, stride=1),MV2_Block(base_channels, 4*base_channels, base_channels, stride=2),MV2_Block(base_channels, 4*base_channels, base_channels, stride=1),MV2_Block(base_channels, 4*base_channels, base_channels, stride=2),# Transformer blockLW_ViT_Transformer_Block(in_channels=base_channels,out_channels=2*base_channels,patch_size=2,heads=4,dim=128),# Final convolutional layernn.Conv2d(2*base_channels, 4*base_channels, kernel_size=1, stride=1),nn.BatchNorm2d(4*base_channels),HSwish())# Global pooling and classifierself.global_pool = nn.AdaptiveAvgPool2d(1)self.dropout = nn.Dropout(0.1) # Added dropout for regularizationself.classifier = nn.Sequential(nn.Linear(4*base_channels, 8*base_channels),nn.BatchNorm1d(8*base_channels),HSwish(),nn.Dropout(0.1), # Added dropout for regularizationnn.Linear(8*base_channels, num_classes))def forward(self, x):x = self.stem(x)x = self.features(x)x = self.global_pool(x)x = torch.flatten(x, 1)x = self.dropout(x)x = self.classifier(x)return xclassifier = LW_ViT()classifier.load_state_dict(torch.load("model/chinese_Character_Classification_handwritten_LW_ViT.pth", weights_only=True, map_location=user_device))classifier = classifier.to(user_device)classifier.eval()"""load classes dict"""with open("model/chinese_classes.json", "r", encoding="utf-8") as f:classes_dict = json.load(f)"""transforms"""class ToSquare(object):"""Transform to make images square by padding the shorter dimension"""def __init__(self, fill=0):self.fill = fill # Fill value for padding (0 = black)def __call__(self, img):w, h = img.size# If already square, return as isif w == h:return img# Calculate target size (max dimension)max_dim = max(w, h)# Calculate paddingpad_w = (max_dim - w) // 2pad_h = (max_dim - h) // 2# Handle odd dimensions (extra pixel on one side)pad_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_imgclass ConvertToRGB(object):"""Convert image to RGB mode"""def __call__(self, img):# Convert any image mode to RGB (including RGBA)return img.convert('RGB')class Contrast(object):"""Randomly adjust contrast"""def __init__(self, p=0.3, factor_range=(0.5, 1.5)):self.p = pself.factor_range = factor_rangedef __call__(self, img):enhancer = ImageEnhance.Contrast(img)return enhancer.enhance(1.5)test_transforms = transforms.Compose([ToSquare(fill=255),transforms.Resize(128),ConvertToRGB(),transforms.ToTensor(),transforms.Normalize(mean=[0.5], std=[0.5])])"""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):# convert input to pil imageif inputimg is None:return Noneif isinstance(inputimg, np.ndarray):pil_img = Image.fromarray(inputimg)elif hasattr(inputimg, 'convert'): # Check if it's already a PIL Imagepil_img = inputimgelse:pil_img = Image.fromarray(np.array(inputimg))pil_img = pil_img.convert("RGB")return pil_imgdef draw_bboxes(img, results):# Create a copy of the input image to draw ondraw_img = img.copy()draw = ImageDraw.Draw(draw_img)# Draw bounding boxes for detected objectsfor box in results[0].boxes.xyxy:x1, y1, x2, y2 = map(int, box) # Convert to integersdraw.rectangle([x1, y1, x2, y2], outline=(255, 0, 0), width=2)return draw_imgdef crop_bboxes_by_reading_order(img, bboxes, written_vertical=False):"""Crop and return image regions in proper reading order.For vertical Chinese:- Group into columns by x-coordinate (clusters whose centers are within avg_width/2)- Order columns right-to-left- Within each column, order top-to-bottom by yFor horizontal:- Group into rows by y-coordinate (clusters within avg_height/2)- Order rows top-to-bottom- Within each row, order left-to-right by x"""# 1) If bboxes is a Tensor, convert to Python listif hasattr(bboxes, "tolist"):bboxes = bboxes.tolist()# 2) Single box -> trivial cropif len(bboxes) <= 1:return [img.crop(tuple(map(int, bbox))) for bbox in bboxes]# 3) Compute centers and average glyph sizecenters = [((x1+x2)/2, (y1+y2)/2) for x1,y1,x2,y2 in bboxes]widths = [x2 - x1 for x1,y1,x2,y2 in bboxes]heights = [y2 - y1 for x1,y1,x2,y2 in bboxes]avg_w = mean(widths)avg_h = mean(heights)# 4) Choose clustering axis and thresholdif written_vertical:coords = [c[0] for c in centers] # x-coordsthreshold = avg_w / 2else:coords = [c[1] for c in centers] # y-coordsthreshold = avg_h / 2# 5) Sort glyphs by the clustering axisorder = sorted(range(len(coords)), key=lambda i: coords[i])# 6) Build clustersclusters = []current = [order[0]]current_mean = coords[order[0]]for 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 incrementallycurrent_mean = mean([coords[i] for i in current])else:clusters.append(current)current = [idx]current_mean = cclusters.append(current)# 7) Order clustersif written_vertical:# Chinese vertical: rightmost column firstclusters.sort(key=lambda grp: mean(coords[i] for i in grp),reverse=True)else:# Horizontal: top row firstclusters.sort(key=lambda grp: mean(coords[i] for i in grp))# 8) Within each cluster, sort by the orthogonal axisfinal_indices = []for grp in clusters:if written_vertical:# sort top-to-bottom by ygrp.sort(key=lambda i: centers[i][1])else:# sort left-to-right by xgrp.sort(key=lambda i: centers[i][0])final_indices.extend(grp)# 9) Crop and returncrops = []for i in final_indices:x1, y1, x2, y2 = map(int, bboxes[i])crops.append(img.crop((x1, y1, x2, y2)))return cropsdef 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)return draw_imgdef select_image(evt: gr.SelectData):selected_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 "", "", ""with torch.inference_mode():results = detection_model(source=pil_img, conf=threshhold_slider)sorted_cropped_images = crop_bboxes_by_reading_order(img=pil_img, bboxes=results[0].boxes.xyxy, written_vertical=is_vertical)chinese_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)pinyin_sentence = " "for 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, translationcss = """.centered-examples {margin: 0 auto !important;justify-content: center !important;gap: 8px !important;min-height: 150px !important; /* Added minimum height */}.centered-examples .thumb {height: 100px !important;width: 100px !important;object-fit: cover !important;margin: 5px !important; /* Added margin between thumbs */}/* 1) Global override: remove any forced sizing on .fixed-height anywhere */.fixed-height.svelte-842rpi.svelte-842rpi {min-height: 0 !important; /* cancel the global min-height */max-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 {min-height: 0 !important; /* zero-out the 55vh/min-height there */max-height: none !important; /* remove the viewport-height cap */height: auto !important; /* let content dictate height */}}""""""gradio app"""example_dir = "examples"example_images = [os.path.join(example_dir, f) for f in os.listdir(example_dir)if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]with gr.Blocks(css=css) as program:gr.Markdown("## DeepTranslate: Chinese OCR with translation to english")gr.Markdown("Upload or select an image and move the slider to detect characters.")gr.Markdown("Make sure that the input image is high resolution and not rotated in any way!")#inputswith gr.Column(scale=1):gallery = gr.Gallery(value=example_images,label="Example Images (Click to Select)",columns=6,allow_preview=False,elem_id="my_media_gallery",elem_classes=["centered-examples"])with gr.Row(scale=2):input_img = gr.Image(label="Input Image ")detection_img = gr.Image(label="Detection Image", interactive= False)# slider and buttonwith gr.Column(scale=1):with gr.Row(scale=3):threshhold_slider = gr.Slider(value=0.25, minimum=0, maximum=0.75, label="Detection Threshhold", step = 0.01)translate_button = gr.Button("Translate To English", variant="primary")is_vertical = gr.Checkbox(value=False, label="Vertiacl Chinese Text?", interactive=True)# outputswith gr.Column(scale=1):with gr.Row(scale=3):chinese_text = gr.TextArea(label="Chinese Text", max_lines= 1000, interactive=False)pinyin_text = gr.TextArea(label="Chinese Pinyin", max_lines= 1000, interactive=False)english_text = gr.TextArea(label="English Text", max_lines= 1000, interactive=False)#function, callingthreshhold_slider.change(fn= move_slider, inputs=[threshhold_slider, input_img], outputs=[detection_img])translate_button.click(fn=translate_text, inputs= [threshhold_slider, is_vertical, input_img], outputs=[chinese_text, pinyin_text, english_text])gallery.select(fn=select_image, inputs=None, outputs=input_img)if __name__ == "__main__":program.launch(share=False)
app.py+533-533