aiqcamp commited on
Commit
a0d5852
ยท
verified ยท
1 Parent(s): 472b6d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -51
app.py CHANGED
@@ -471,6 +471,11 @@ footer {
471
  .btn {
472
  display: flex;
473
  }
 
 
 
 
 
474
  """])
475
 
476
 
@@ -492,7 +497,6 @@ def easy_scaler(img):
492
  return upscaler(img)
493
 
494
  def handle_upscaler(img):
495
-
496
  w, h = img.size
497
  if w*h > 2 * (10 ** 6):
498
  return hard_scaler(img)
@@ -538,7 +542,6 @@ def upscaler(
538
  )
539
 
540
  log(f'RET upscaler')
541
-
542
  return enhanced_image
543
 
544
  def get_tensor_length(tensor):
@@ -551,7 +554,7 @@ def get_tensor_length(tensor):
551
  def _summarize(text):
552
  log(f'CALL _summarize')
553
  prefix = "summarize: "
554
- toks = tokenizer.encode( prefix + text, return_tensors="pt", truncation=False)
555
  gen = model.generate(
556
  toks,
557
  length_penalty=0.1,
@@ -572,9 +575,7 @@ def summarize(text, max_words=100):
572
  if words_length >= 510:
573
  while words_length >= 510:
574
  words = text.split()
575
- sum = _summarize(
576
- " ".join(words[0:510])
577
- ) + " ".join(words[510:])
578
  if summ == text:
579
  return text
580
  text = summ
@@ -597,7 +598,6 @@ def generate_random_string(length):
597
  def add_text_above_image(img,top_title=None,bottom_title=None):
598
 
599
  w, h = img.size
600
-
601
  draw = ImageDraw.Draw(img,mode="RGBA")
602
 
603
  labels_distance = 1/3
@@ -610,7 +610,15 @@ def add_text_above_image(img,top_title=None,bottom_title=None):
610
  x = math.ceil((w - textwidth) / 2)
611
  y = h - (textheight * rows / 2) - (h / 2)
612
  y = math.ceil(y - (h / 2 * labels_distance))
613
- draw.text((x, y), top_title, (255,255,255), font=font, spacing=2, stroke_width=math.ceil(textheight/20), stroke_fill=(0,0,0))
 
 
 
 
 
 
 
 
614
 
615
  if bottom_title:
616
  rows = len(bottom_title.split("\n"))
@@ -620,7 +628,15 @@ def add_text_above_image(img,top_title=None,bottom_title=None):
620
  x = math.ceil((w - textwidth) / 2)
621
  y = h - (textheight * rows / 2) - (h / 2)
622
  y = math.ceil(y + (h / 2 * labels_distance))
623
- draw.text((x, y), bottom_title, (0,0,0), font=font, spacing=2, stroke_width=math.ceil(textheight/20), stroke_fill=(255,255,255))
 
 
 
 
 
 
 
 
624
 
625
  return img
626
 
@@ -769,10 +785,6 @@ class BaseError(Exception):
769
  """
770
 
771
  def __init__(self, val, message):
772
- """
773
- @param val: actual value
774
- @param message: message shown to the user
775
- """
776
  self.val = val
777
  self.message = message
778
  super().__init__()
@@ -866,7 +878,6 @@ class RequestError(Exception):
866
  return self.message
867
 
868
 
869
-
870
  class TooManyRequests(Exception):
871
  """
872
  exception thrown if an error occurred during the request call, e.g a connection problem.
@@ -884,6 +895,7 @@ class TooManyRequests(Exception):
884
  def __str__(self):
885
  return self.message
886
 
 
887
  class ServerException(Exception):
888
  """
889
  Default YandexTranslate exception from the official website
@@ -913,14 +925,7 @@ def is_empty(text: str) -> bool:
913
 
914
  def request_failed(status_code: int) -> bool:
915
  """Check if a request has failed or not.
916
- A request is considered successfull if the status code is in the 2** range.
917
-
918
- Args:
919
- status_code (int): status code of the request
920
-
921
- Returns:
922
- bool: indicates request failure
923
- """
924
  if status_code > 299 or status_code < 200:
925
  return True
926
  return False
@@ -936,12 +941,10 @@ def is_input_valid(
936
  @param text: text to translate
937
  @return: bool
938
  """
939
-
940
  if not isinstance(text, str):
941
  raise NotValidPayload(text)
942
  if max_chars and (not min_chars <= len(text) < max_chars):
943
  raise NotValidLength(text, min_chars, max_chars)
944
-
945
  return True
946
 
947
  class BaseTranslator(ABC):
@@ -1037,7 +1040,7 @@ class BaseTranslator(ABC):
1037
  """
1038
  check if the language is supported by the translator
1039
  @param language: a string for 1 language
1040
- @return: bool or raise an Exception
1041
  """
1042
  if (
1043
  language == "auto"
@@ -1061,12 +1064,10 @@ class BaseTranslator(ABC):
1061
 
1062
  def _read_docx(self, f: str):
1063
  import docx2txt
1064
-
1065
  return docx2txt.process(f)
1066
 
1067
  def _read_pdf(self, f: str):
1068
  import pypdf
1069
-
1070
  reader = pypdf.PdfReader(f)
1071
  page = reader.pages[0]
1072
  return page.extract_text()
@@ -1090,7 +1091,6 @@ class BaseTranslator(ABC):
1090
 
1091
  if ext == ".docx":
1092
  text = self._read_docx(f=str(path))
1093
-
1094
  elif ext == ".pdf":
1095
  text = self._read_pdf(f=str(path))
1096
  else:
@@ -1176,6 +1176,7 @@ class GoogleTranslator(BaseTranslator):
1176
  element = soup.find(self._element_tag, self._alt_element_query)
1177
  if not element:
1178
  raise TranslationNotFound(text)
 
1179
  if element.get_text(strip=True) == text.strip():
1180
  to_translate_alpha = "".join(
1181
  ch for ch in text.strip() if ch.isalnum()
@@ -1246,22 +1247,20 @@ def translate(txt,to_lang="en",from_lang="auto"):
1246
  return translation.lower()
1247
 
1248
  def handle_generation(h,w,d):
1249
-
1250
  log(f'CALL handle_generate')
1251
-
1252
  difficulty_points = 0
1253
 
1254
- toks_len = get_tensor_length(tokenizer.encode( d, return_tensors="pt", truncation=False))
1255
  if toks_len > 500:
1256
- difficulty_points + 2
1257
  elif toks_len > 50:
1258
- difficulty_points + 1
1259
 
1260
  pxs = h*w
1261
  if pxs > 2 * (10 ** 6):
1262
- difficulty_points + 2
1263
  elif pxs > 1 * (10 ** 6):
1264
- difficulty_points + 1
1265
 
1266
  if difficulty_points < 2:
1267
  return easy_generation(h,w,d)
@@ -1283,7 +1282,6 @@ def hard_generation(h,w,d):
1283
  return generation(h,w,d)
1284
 
1285
  def generation(h,w,d):
1286
-
1287
  if len(d) > 0:
1288
  d = re.sub(r",( ){1,}",". ",d)
1289
  d_lines = re.split(r"([\n]){1,}", d)
@@ -1295,12 +1293,11 @@ def generation(h,w,d):
1295
  d = " ".join(d_lines)
1296
 
1297
  d = re.sub(r"([ \t]){1,}", " ", d).lower().strip()
1298
- d = d if d == "" else summarize(translate(d),max_words=50)
1299
  d = re.sub(r"([ \t]){1,}", " ", d)
1300
  d = re.sub(r"(\. \.)", ".", d)
1301
 
1302
  neg = f"Textual, Text, Signs, Labels, Titles, Unreal, Exceptional, Irregular, Unusual, Blurry, Smoothed, Polished, Worst Quality, Worse Quality, Painted, Movies Quality."
1303
- q = "\""
1304
  pos = f'Accurate, Detailed, Realistic.{ "" if d == "" else " " + d }'
1305
 
1306
  print(f"""
@@ -1321,15 +1318,15 @@ def generation(h,w,d):
1321
  max_sequence_length=seq,
1322
  generator=torch.Generator(device).manual_seed(random.randint(0, MAX_SEED))
1323
  ).images[0]
1324
-
1325
  return img
1326
-
1327
  # entry
1328
 
1329
  if __name__ == "__main__":
1330
- with gr.Blocks(theme=gr.themes.Citrus(),css=css) as demo:
 
1331
  gr.Markdown(f"""
1332
- # Text-to-Image generator
1333
  """)
1334
  gr.Markdown(f"""
1335
  ### Realistic. Upscalable. Multilingual.
@@ -1337,7 +1334,6 @@ if __name__ == "__main__":
1337
 
1338
  with gr.Row():
1339
  with gr.Column(scale=2):
1340
-
1341
  height = gr.Slider(
1342
  label="Height (px)",
1343
  minimum=512,
@@ -1345,7 +1341,6 @@ if __name__ == "__main__":
1345
  step=16,
1346
  value=1024,
1347
  )
1348
-
1349
  width = gr.Slider(
1350
  label="Width (px)",
1351
  minimum=512,
@@ -1354,7 +1349,7 @@ if __name__ == "__main__":
1354
  value=1024,
1355
  )
1356
 
1357
- run = gr.Button("Generate",elem_classes="btn")
1358
 
1359
  top = gr.Textbox(
1360
  placeholder="Top title",
@@ -1370,21 +1365,51 @@ if __name__ == "__main__":
1370
  )
1371
 
1372
  data = gr.Textbox(
1373
- placeholder="Input data",
1374
  value="",
1375
  container=False,
1376
  max_lines=100
1377
  )
1378
 
1379
  with gr.Column():
1380
- cover = gr.Image(interactive=False,container=False,elem_classes="image-container", label="Result", show_label=True, type='pil', show_share_button=False)
1381
- upscale_now = gr.Button("Upscale x2",elem_classes="btn")
1382
- add_titles = gr.Button("Add title(s)",elem_classes="btn")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1383
 
 
1384
  gr.on(
1385
  triggers=[run.click],
1386
  fn=handle_generation,
1387
- inputs=[height,width,data],
1388
  outputs=[cover]
1389
  )
1390
  upscale_now.click(
@@ -1394,7 +1419,7 @@ if __name__ == "__main__":
1394
  )
1395
  add_titles.click(
1396
  fn=add_text_above_image,
1397
- inputs=[cover,top,bottom],
1398
  outputs=[cover]
1399
  )
1400
 
 
471
  .btn {
472
  display: flex;
473
  }
474
+
475
+ /* Added background gradient for a more colorful look */
476
+ .gradio-container {
477
+ background: linear-gradient(to right, #ffecd2, #fcb69f) !important;
478
+ }
479
  """])
480
 
481
 
 
497
  return upscaler(img)
498
 
499
  def handle_upscaler(img):
 
500
  w, h = img.size
501
  if w*h > 2 * (10 ** 6):
502
  return hard_scaler(img)
 
542
  )
543
 
544
  log(f'RET upscaler')
 
545
  return enhanced_image
546
 
547
  def get_tensor_length(tensor):
 
554
  def _summarize(text):
555
  log(f'CALL _summarize')
556
  prefix = "summarize: "
557
+ toks = tokenizer.encode(prefix + text, return_tensors="pt", truncation=False)
558
  gen = model.generate(
559
  toks,
560
  length_penalty=0.1,
 
575
  if words_length >= 510:
576
  while words_length >= 510:
577
  words = text.split()
578
+ summ = _summarize(" ".join(words[0:510])) + " ".join(words[510:])
 
 
579
  if summ == text:
580
  return text
581
  text = summ
 
598
  def add_text_above_image(img,top_title=None,bottom_title=None):
599
 
600
  w, h = img.size
 
601
  draw = ImageDraw.Draw(img,mode="RGBA")
602
 
603
  labels_distance = 1/3
 
610
  x = math.ceil((w - textwidth) / 2)
611
  y = h - (textheight * rows / 2) - (h / 2)
612
  y = math.ceil(y - (h / 2 * labels_distance))
613
+ draw.text(
614
+ (x, y),
615
+ top_title,
616
+ (255,255,255),
617
+ font=font,
618
+ spacing=2,
619
+ stroke_width=math.ceil(textheight/20),
620
+ stroke_fill=(0,0,0)
621
+ )
622
 
623
  if bottom_title:
624
  rows = len(bottom_title.split("\n"))
 
628
  x = math.ceil((w - textwidth) / 2)
629
  y = h - (textheight * rows / 2) - (h / 2)
630
  y = math.ceil(y + (h / 2 * labels_distance))
631
+ draw.text(
632
+ (x, y),
633
+ bottom_title,
634
+ (0,0,0),
635
+ font=font,
636
+ spacing=2,
637
+ stroke_width=math.ceil(textheight/20),
638
+ stroke_fill=(255,255,255)
639
+ )
640
 
641
  return img
642
 
 
785
  """
786
 
787
  def __init__(self, val, message):
 
 
 
 
788
  self.val = val
789
  self.message = message
790
  super().__init__()
 
878
  return self.message
879
 
880
 
 
881
  class TooManyRequests(Exception):
882
  """
883
  exception thrown if an error occurred during the request call, e.g a connection problem.
 
895
  def __str__(self):
896
  return self.message
897
 
898
+
899
  class ServerException(Exception):
900
  """
901
  Default YandexTranslate exception from the official website
 
925
 
926
  def request_failed(status_code: int) -> bool:
927
  """Check if a request has failed or not.
928
+ A request is considered successful if the status code is in the 2** range."""
 
 
 
 
 
 
 
929
  if status_code > 299 or status_code < 200:
930
  return True
931
  return False
 
941
  @param text: text to translate
942
  @return: bool
943
  """
 
944
  if not isinstance(text, str):
945
  raise NotValidPayload(text)
946
  if max_chars and (not min_chars <= len(text) < max_chars):
947
  raise NotValidLength(text, min_chars, max_chars)
 
948
  return True
949
 
950
  class BaseTranslator(ABC):
 
1040
  """
1041
  check if the language is supported by the translator
1042
  @param language: a string for 1 language
1043
+ @return: bool
1044
  """
1045
  if (
1046
  language == "auto"
 
1064
 
1065
  def _read_docx(self, f: str):
1066
  import docx2txt
 
1067
  return docx2txt.process(f)
1068
 
1069
  def _read_pdf(self, f: str):
1070
  import pypdf
 
1071
  reader = pypdf.PdfReader(f)
1072
  page = reader.pages[0]
1073
  return page.extract_text()
 
1091
 
1092
  if ext == ".docx":
1093
  text = self._read_docx(f=str(path))
 
1094
  elif ext == ".pdf":
1095
  text = self._read_pdf(f=str(path))
1096
  else:
 
1176
  element = soup.find(self._element_tag, self._alt_element_query)
1177
  if not element:
1178
  raise TranslationNotFound(text)
1179
+
1180
  if element.get_text(strip=True) == text.strip():
1181
  to_translate_alpha = "".join(
1182
  ch for ch in text.strip() if ch.isalnum()
 
1247
  return translation.lower()
1248
 
1249
  def handle_generation(h,w,d):
 
1250
  log(f'CALL handle_generate')
 
1251
  difficulty_points = 0
1252
 
1253
+ toks_len = get_tensor_length(tokenizer.encode(d, return_tensors="pt", truncation=False))
1254
  if toks_len > 500:
1255
+ difficulty_points += 2
1256
  elif toks_len > 50:
1257
+ difficulty_points += 1
1258
 
1259
  pxs = h*w
1260
  if pxs > 2 * (10 ** 6):
1261
+ difficulty_points += 2
1262
  elif pxs > 1 * (10 ** 6):
1263
+ difficulty_points += 1
1264
 
1265
  if difficulty_points < 2:
1266
  return easy_generation(h,w,d)
 
1282
  return generation(h,w,d)
1283
 
1284
  def generation(h,w,d):
 
1285
  if len(d) > 0:
1286
  d = re.sub(r",( ){1,}",". ",d)
1287
  d_lines = re.split(r"([\n]){1,}", d)
 
1293
  d = " ".join(d_lines)
1294
 
1295
  d = re.sub(r"([ \t]){1,}", " ", d).lower().strip()
1296
+ d = d if d == "" else summarize(translate(d), max_words=50)
1297
  d = re.sub(r"([ \t]){1,}", " ", d)
1298
  d = re.sub(r"(\. \.)", ".", d)
1299
 
1300
  neg = f"Textual, Text, Signs, Labels, Titles, Unreal, Exceptional, Irregular, Unusual, Blurry, Smoothed, Polished, Worst Quality, Worse Quality, Painted, Movies Quality."
 
1301
  pos = f'Accurate, Detailed, Realistic.{ "" if d == "" else " " + d }'
1302
 
1303
  print(f"""
 
1318
  max_sequence_length=seq,
1319
  generator=torch.Generator(device).manual_seed(random.randint(0, MAX_SEED))
1320
  ).images[0]
 
1321
  return img
1322
+
1323
  # entry
1324
 
1325
  if __name__ == "__main__":
1326
+ # Changed the theme to a more colorful one and updated the title
1327
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="lime"), css=css) as demo:
1328
  gr.Markdown(f"""
1329
+ # Multilingual Images
1330
  """)
1331
  gr.Markdown(f"""
1332
  ### Realistic. Upscalable. Multilingual.
 
1334
 
1335
  with gr.Row():
1336
  with gr.Column(scale=2):
 
1337
  height = gr.Slider(
1338
  label="Height (px)",
1339
  minimum=512,
 
1341
  step=16,
1342
  value=1024,
1343
  )
 
1344
  width = gr.Slider(
1345
  label="Width (px)",
1346
  minimum=512,
 
1349
  value=1024,
1350
  )
1351
 
1352
+ run = gr.Button("Generate", elem_classes="btn")
1353
 
1354
  top = gr.Textbox(
1355
  placeholder="Top title",
 
1365
  )
1366
 
1367
  data = gr.Textbox(
1368
+ placeholder="Input data (text/prompt)",
1369
  value="",
1370
  container=False,
1371
  max_lines=100
1372
  )
1373
 
1374
  with gr.Column():
1375
+ cover = gr.Image(
1376
+ interactive=False,
1377
+ container=False,
1378
+ elem_classes="image-container",
1379
+ label="Result",
1380
+ show_label=True,
1381
+ type='pil',
1382
+ show_share_button=False
1383
+ )
1384
+ upscale_now = gr.Button("Upscale x2", elem_classes="btn")
1385
+ add_titles = gr.Button("Add title(s)", elem_classes="btn")
1386
+
1387
+ gr.Markdown("---")
1388
+
1389
+ # Bottom row explanation or details
1390
+ gr.Markdown("""
1391
+ ## ๊ธฐ๋Šฅ ์„ธ๋ถ€ ์„ค๋ช… (Features)
1392
+ 1. **ํ…์ŠคํŠธ ์ž…๋ ฅ**: ๋‹ค์–‘ํ•œ ์–ธ์–ด๋กœ ํ…์ŠคํŠธ ์ž…๋ ฅ ์‹œ ์ž๋™ ๋ฒˆ์—ญ ๋ฐ ์š”์•ฝ ํ›„ ์ด๋ฏธ์ง€๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
1393
+ 2. **์ด๋ฏธ์ง€ ํฌ๊ธฐ ์กฐ์ ˆ**: ์Šฌ๋ผ์ด๋”๋ฅผ ํ†ตํ•ด ์ƒ์„ฑ๋  ์ด๋ฏธ์ง€์˜ ํฌ๊ธฐ๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
1394
+ 3. **์˜ค๋ฒ„๋ ˆ์ด ํ…์ŠคํŠธ**: ์ด๋ฏธ์ง€ ์œ„์— ์ƒ๋‹จ/ํ•˜๋‹จ ํƒ€์ดํ‹€์„ ์ถ”๊ฐ€ํ•˜์—ฌ ๊ฐ„๋‹จํ•œ ๋ผ๋ฒจ๋ง์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.
1395
+ 4. **๊ณ ํ™”์งˆ ์—…์Šค์ผ€์ผ**: 'Upscale x2' ๋ฒ„ํŠผ์„ ํ†ตํ•ด ์ด๋ฏธ์ง€ ํ’ˆ์งˆ์„ ํ–ฅ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
1396
+ 5. **์ž๋™ ์ƒ์„ฑ ๋‚œ์ด๋„ ์กฐ์ ˆ**: ์ž…๋ ฅ ํ…์ŠคํŠธ์™€ ์ด๋ฏธ์ง€ ํฌ๊ธฐ์— ๋”ฐ๋ผ GPU ์‚ฌ์šฉ์‹œ๊ฐ„์ด ์ž๋™์œผ๋กœ ์กฐ์ ˆ๋ฉ๋‹ˆ๋‹ค.
1397
+ ---
1398
+ """)
1399
+
1400
+ gr.Markdown("""
1401
+ ### ์ด์šฉ ๊ฐ€์ด๋“œ
1402
+ 1. ์›ํ•˜๋Š” ์ด๋ฏธ์ง€ ์‚ฌ์ด์ฆˆ์™€ ํ…์ŠคํŠธ(๋‹ค๊ตญ์–ด ๊ฐ€๋Šฅ)๋ฅผ ์ž…๋ ฅ ํ›„ **Generate** ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜์„ธ์š”.
1403
+ 2. ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€๋ฅผ ํ™•์ธํ•œ ๋’ค, **Upscale x2** ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋” ๋†’์€ ํ•ด์ƒ๋„๋กœ ์—…์Šค์ผ€์ผ ๋ฉ๋‹ˆ๋‹ค.
1404
+ 3. **Add title(s)** ๋ฒ„ํŠผ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ด๋ฏธ์ง€ ์œ„์— ํƒ€์ดํ‹€์„ ์‰ฝ๊ฒŒ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
1405
+ 4. ๊ธฐ๋Šฅ ์„ธ๋ถ€ ์„ค๋ช…์€ ์ƒ๋‹จ์˜ ์ž…๋ ฅํ•ญ๋ชฉ๋“ค์„ ํ†ตํ•ด ํ…Œ์ŠคํŠธํ•ด ๋ณด์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
1406
+ """)
1407
 
1408
+ # Event wiring
1409
  gr.on(
1410
  triggers=[run.click],
1411
  fn=handle_generation,
1412
+ inputs=[height, width, data],
1413
  outputs=[cover]
1414
  )
1415
  upscale_now.click(
 
1419
  )
1420
  add_titles.click(
1421
  fn=add_text_above_image,
1422
+ inputs=[cover, top, bottom],
1423
  outputs=[cover]
1424
  )
1425