IncreasingLoss commited on
Commit
e3858d2
·
verified ·
1 Parent(s): 3975839

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -13
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import gradio as gr
2
  import torch
3
  import torch.nn as nn
4
- import torch.nn.functional as F
5
  from torchvision import transforms
6
  import numpy as np
7
  from ultralytics import YOLO
@@ -10,6 +10,8 @@ from pypinyin import pinyin
10
  from PIL import Image, ImageDraw, ImageEnhance
11
  import json
12
  import os
 
 
13
 
14
  """yolo model"""
15
  user_device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -22,7 +24,7 @@ detection_model = YOLO("model/yolo_chinese_m.pt").to(user_device).eval()
22
  class HSwish(nn.Module):
23
  """Hard Swish activation function"""
24
  def forward(self, x):
25
- out = x * F.relu6(x + 3, inplace=True) / 6
26
  return out
27
 
28
  class MV2_Block(nn.Module):
@@ -194,7 +196,7 @@ classifier.load_state_dict(torch.load("model/chinese_Character_Classification_ha
194
  classifier.to(user_device).eval()
195
 
196
  """load classes dict"""
197
- with open("model/LW_Vit/chinese_classes.json", "r", encoding="utf-8") as f:
198
  classes_dict = json.load(f)
199
 
200
  """transforms"""
@@ -223,11 +225,11 @@ class ToSquare(object):
223
  pad_w_extra = (max_dim - w) % 2
224
  pad_h_extra = (max_dim - h) % 2
225
 
226
- # Create padding tuple (left, top, right, bottom)
227
- padding = (pad_w, pad_h, pad_w + pad_w_extra, pad_h + pad_h_extra)
228
 
229
  # Create new padded image
230
- padded_img = transforms.functional.pad(img, padding, fill=self.fill)
231
 
232
  return padded_img
233
 
@@ -259,13 +261,12 @@ test_transforms = transforms.Compose([
259
  """import llm"""
260
  llm = Llama.from_pretrained(
261
  repo_id="IncreasingLoss/FineTunedTranslation_Yi-1.5-9B-Chat-Q6_K",
262
- filename="*.gguf",
263
  n_ctx=4096,
264
  n_gpu_layers=-1,
265
  verbose=False
266
  )
267
 
268
-
269
  """app functions"""
270
  def convert_to_pil(inputimg):
271
  # convert input to pil image
@@ -340,7 +341,7 @@ def crop_bboxes_by_reading_order(img, bboxes, written_vertical=False):
340
 
341
  for idx in order[1:]:
342
  c = coords[idx]
343
- # if within threshold of this cluster’s mean, add; else start new
344
  if abs(c - current_mean) <= threshold:
345
  current.append(idx)
346
  # update cluster mean incrementally
@@ -386,6 +387,9 @@ def crop_bboxes_by_reading_order(img, bboxes, written_vertical=False):
386
 
387
  def move_slider(threshhold_slider, input_img):
388
  pil_img = convert_to_pil(input_img)
 
 
 
389
  with torch.inference_mode():
390
  results = detection_model(source=pil_img, conf=threshhold_slider)
391
  draw_img = draw_bboxes(pil_img, results)
@@ -400,6 +404,9 @@ def select_image(evt: gr.SelectData):
400
  def translate_text(threshhold_slider, is_vertical, input_img):
401
  # convert input to pil image
402
  pil_img = convert_to_pil(input_img)
 
 
 
403
 
404
  with torch.inference_mode():
405
  results = detection_model(source=pil_img, conf=threshhold_slider)
@@ -413,7 +420,6 @@ def translate_text(threshhold_slider, is_vertical, input_img):
413
  chinese_charcter = classes_dict[class_idx]
414
  chinese_text += chinese_charcter
415
 
416
- #chinese_text = "这是一句测试语句,用来检验我的深度翻译计算机语言模型。"
417
  pinyin_text = pinyin(chinese_text)
418
  pinyin_sentence = " "
419
  for pin in pinyin_text:
@@ -426,7 +432,7 @@ def translate_text(threshhold_slider, is_vertical, input_img):
426
  2. Respond only with the translated English text.
427
  English translation: """
428
 
429
- #try:
430
  output = llm(
431
  prompt,
432
  max_tokens=min(len(chinese_text)*2, 512), # More reasonable token limit with safety cap
@@ -435,7 +441,8 @@ def translate_text(threshhold_slider, is_vertical, input_img):
435
  temperature=0.3, # Slightly higher temperature for more natural language
436
  frequency_penalty=.5, # Penalize repetition of tokens - higher values discourage repetition
437
  presence_penalty=.5, # Penalize tokens that have appeared at all - prevents topic repetition
438
- top_p=0.9 # Nucleus sampling - restricts to top 90% most likely tokens for more coherent output
 
439
  )
440
 
441
  # Extract the translation
@@ -470,7 +477,7 @@ css = """
470
  max-height: none !important; /* cancel the global max-height */
471
  height: auto !important; /* allow auto height */
472
  }
473
- /* 2) Same-query override: mirror Gradio’s media query exactly */
474
  @media (min-width: 1280px) {
475
  /* target the exact same class chain inside the breakpoint */
476
  .fixed-height.svelte-842rpi.svelte-842rpi {
 
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
 
10
  from PIL import Image, ImageDraw, ImageEnhance
11
  import json
12
  import os
13
+ import torchvision.transforms.functional as F
14
+
15
 
16
  """yolo model"""
17
  user_device = "cuda" if torch.cuda.is_available() else "cpu"
 
24
  class HSwish(nn.Module):
25
  """Hard Swish activation function"""
26
  def forward(self, x):
27
+ out = x * FU.relu6(x + 3, inplace=True) / 6
28
  return out
29
 
30
  class MV2_Block(nn.Module):
 
196
  classifier.to(user_device).eval()
197
 
198
  """load classes dict"""
199
+ with open("model/chinese_classes.json", "r", encoding="utf-8") as f:
200
  classes_dict = json.load(f)
201
 
202
  """transforms"""
 
225
  pad_w_extra = (max_dim - w) % 2
226
  pad_h_extra = (max_dim - h) % 2
227
 
228
+ # Create padding list (left, top, right, bottom) - FIX #1: Use list instead of tuple
229
+ padding = [pad_w, pad_h, pad_w + pad_w_extra, pad_h + pad_h_extra]
230
 
231
  # Create new padded image
232
+ padded_img = F.pad(img, padding, self.fill)
233
 
234
  return padded_img
235
 
 
261
  """import llm"""
262
  llm = Llama.from_pretrained(
263
  repo_id="IncreasingLoss/FineTunedTranslation_Yi-1.5-9B-Chat-Q6_K",
264
+ filename="*.gguf", # or specify exact file name if only one GGUF in repo
265
  n_ctx=4096,
266
  n_gpu_layers=-1,
267
  verbose=False
268
  )
269
 
 
270
  """app functions"""
271
  def convert_to_pil(inputimg):
272
  # convert input to pil image
 
341
 
342
  for idx in order[1:]:
343
  c = coords[idx]
344
+ # if within threshold of this cluster's mean, add; else start new
345
  if abs(c - current_mean) <= threshold:
346
  current.append(idx)
347
  # update cluster mean incrementally
 
387
 
388
  def move_slider(threshhold_slider, input_img):
389
  pil_img = convert_to_pil(input_img)
390
+ # FIX #2: Add null check for pil_img
391
+ if pil_img is None:
392
+ return None
393
  with torch.inference_mode():
394
  results = detection_model(source=pil_img, conf=threshhold_slider)
395
  draw_img = draw_bboxes(pil_img, results)
 
404
  def translate_text(threshhold_slider, is_vertical, input_img):
405
  # convert input to pil image
406
  pil_img = convert_to_pil(input_img)
407
+ # FIX #2: Add null check for pil_img
408
+ if pil_img is None:
409
+ return "", "", ""
410
 
411
  with torch.inference_mode():
412
  results = detection_model(source=pil_img, conf=threshhold_slider)
 
420
  chinese_charcter = classes_dict[class_idx]
421
  chinese_text += chinese_charcter
422
 
 
423
  pinyin_text = pinyin(chinese_text)
424
  pinyin_sentence = " "
425
  for pin in pinyin_text:
 
432
  2. Respond only with the translated English text.
433
  English translation: """
434
 
435
+ # FIX #3: Disable streaming to get direct dict access
436
  output = llm(
437
  prompt,
438
  max_tokens=min(len(chinese_text)*2, 512), # More reasonable token limit with safety cap
 
441
  temperature=0.3, # Slightly higher temperature for more natural language
442
  frequency_penalty=.5, # Penalize repetition of tokens - higher values discourage repetition
443
  presence_penalty=.5, # Penalize tokens that have appeared at all - prevents topic repetition
444
+ top_p=0.9, # Nucleus sampling - restricts to top 90% most likely tokens for more coherent output
445
+ stream=False # Explicitly disable streaming to get a dict response
446
  )
447
 
448
  # Extract the translation
 
477
  max-height: none !important; /* cancel the global max-height */
478
  height: auto !important; /* allow auto height */
479
  }
480
+ /* 2) Same-query override: mirror Gradio's media query exactly */
481
  @media (min-width: 1280px) {
482
  /* target the exact same class chain inside the breakpoint */
483
  .fixed-height.svelte-842rpi.svelte-842rpi {