this is based on calsyslab project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.5 KiB

  1. from deep_translator import GoogleTranslator
  2. # For the arguments source and target, you can use the name of the language or its abbreviation
  3. # chinese (simplified): zh-CN, english: en, korean: ko, persian: fa, russian: ru
  4. def translate(input_text: str, source: str, target='english') -> str:
  5. if len(input_text.strip()) == 0:
  6. return input_text
  7. batch_size = 4999
  8. batches = []
  9. whitespaces = []
  10. start = 0
  11. translated_text = ''
  12. while not input_text[start].strip():
  13. translated_text += input_text[start]
  14. start += 1
  15. # A while loop that will continue as long as start is less than the total length
  16. # of the HTML content (len(input_text)). This ensures that we process the entire content.
  17. while start < len(input_text):
  18. whitespace = ''
  19. # Set the end index for the current batch
  20. end = start + batch_size
  21. # If end is beyond the end of the content, we don't need to adjust it.
  22. if end < len(input_text):
  23. # A while loop to adjust the end index so that it doesn't split a word.
  24. # It continues as long as end is within the content (end < len(input_text)) and
  25. # the character at the end position is not a whitespace (input_text[end].strip()
  26. # returns True for non-whitespace characters).
  27. while end < len(input_text) and input_text[end].strip():
  28. # The inner while loop, decrements the end index by 1. This moves the end index
  29. # backwards until it reaches a whitespace character, ensuring that we don't split a word.
  30. end -= 1
  31. while not input_text[end].strip():
  32. whitespace = input_text[end] + whitespace
  33. end -= 1
  34. else:
  35. end = len(input_text) - 1
  36. while not input_text[end].strip():
  37. whitespace = input_text[end] + whitespace
  38. end -= 1
  39. # This line extracts a substring from the HTML content, starting from the start index
  40. # and ending at the end index. This substring is our batch.
  41. batch = input_text[start: end + 1]
  42. # Add our batch to the batches list
  43. batches.append(batch)
  44. whitespaces.append(whitespace)
  45. # Updates our start index for the next batch
  46. start = end + 1 + len(whitespace)
  47. translated_batches = GoogleTranslator(source, target).translate_batch(batches)
  48. for batch, whitespace in zip(translated_batches, whitespaces):
  49. translated_text += batch + whitespace
  50. return translated_text