nicuf

DeepL-trans2

Jul 8th, 2021
1,669
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 KB | None | 0 0
  1. ROMANIAN: https://neculaifantanaru.com/regex-python-translate-beautifulsoup-deepl-html-tags-contains-keywords.html
  2.  
  3. ENGLISH: https://neculaifantanaru.com/en/regex-python-translate-beautifulsoup-deepl-html-tags-contains-keywords.html
  4.  
  5.  
  6. from bs4 import BeautifulSoup
  7. from bs4.formatter import HTMLFormatter
  8. import requests
  9. import json
  10. import re
  11.  
  12. class UnsortedAttributes(HTMLFormatter):
  13.     def attributes(self, tag):
  14.         for k, v in tag.attrs.items():
  15.             yield k, v
  16.  
  17. files_from_folder = r"c:\Users\Castel\Videos"
  18.  
  19. use_translate_folder = False
  20.  
  21. destination_language = 'nl'
  22.  
  23. extension_file = ".html"
  24. pattern1 = r'<p class="text_obisnuit">.*(( the | you | which | have | had | then | that | must | make | from | else | does | get | will | make | made | yours | can | your | doesn | their | could | from | at | of | my | an | by | with | are | his | him | she | he | it | may | seem | and | for | else | while | which | be | these | let | ask | has | as | won | keep | but | everything | without | thinking | about | just | to | doesn | if | each | try | I’m | them | one | more | much | on | all | even | over | seems ).*){3,}.*</p>'
  25. pattern2 = r'<p class="text_obisnuit2">.*(( the | you | which | have | had | then | that | must | make | from | else | does | get | will | make | made | yours | can | your | doesn | their | could | from | at | of | my | an | by | with | are | his | him | she | he | it | may | seem | and | for | else | while | which | be | these | let | ask | has | as | won | keep | but | everything | without | thinking | about | just | to | doesn | if | each | try | I’m | them | one | more | much | on | all | even | over | seems ).*){3,}.*</p>'
  26. pattern3 = r'<title>.*(( the | you | which | have | had | then | that | must | make | from | else | does | get | will | make | made | yours | can | your | doesn | their | could | from | at | of | my | an | by | with | are | his | him | she | he | it | may | seem | and | for | else | while | which | be | these | let | ask | has | as | won | keep | but | everything | without | thinking | about | just | to | doesn | if | each | try | I’m | them | one | more | much | on | all | even | over | seems ).*){3,}.*</title>'
  27. pattern4 = r'<meta name="description" content=.*(( the | you | which | have | had | then | that | must | make | from | else | does | get | will | make | made | yours | can | your | doesn | their | could | from | at | of | my | an | by | with | are | his | him | she | he | it | may | seem | and | for | else | while | which | be | these | let | ask | has | as | won | keep | but | everything | without | thinking | about | just | to | doesn | if | each | try | I’m | them | one | more | much | on | all | even | over | seems ).*){3,}.*>'
  28.  
  29. patterns = [pattern1, pattern2, pattern3, pattern4]
  30. import os
  31.  
  32. directory = os.fsencode(files_from_folder)
  33.  
  34. def recursively_translate(node):
  35.     for x in range(len(node.contents)):
  36.         if isinstance(node.contents[x], str):
  37.             if node.contents[x].strip() != '':
  38.                 try:
  39.                     newtext = requests.post('https://api-free.deepl.com/v2/translate',
  40.                     data={'auth_key':'YOUR-CODE:fx',
  41.                           'text':node.contents[x],
  42.                           'target_lang':destination_language
  43.                           }).content
  44.                     node.contents[x].replaceWith(json.loads(newtext)['translations'][0]['text'])
  45.                 except:
  46.                     pass
  47.         elif node.contents[x] != None:
  48.             recursively_translate(node.contents[x])
  49.  
  50. for file in os.listdir(directory):
  51.     filename = os.fsdecode(file)
  52.     print(filename)
  53.     if filename == 'y_key_e479323ce281e459.html' or filename == 'TS_4fg4_tr78.html':
  54.         continue
  55.     if filename.endswith(extension_file):
  56.         with open(os.path.join(files_from_folder, filename), encoding='utf-8') as html:
  57.             page = html.read()
  58.             updated = False
  59.             for pattern in patterns:
  60.                 for x in re.finditer(pattern, page):
  61.                     updated = True
  62.                     new = x.group(0)
  63.                     soup = BeautifulSoup(new, 'html.parser')
  64.                     if pattern != pattern4:
  65.                         recursively_translate(soup)
  66.                     else:
  67.                         meta = soup.find('meta')
  68.                         newtext = requests.post('https://api-free.deepl.com/v2/translate',
  69.                         data={'auth_key':'YOUR-CODE:fx',
  70.                               'text':meta['content'],
  71.                               'target_lang':destination_language
  72.                               }).content
  73.                         meta['content'] = json.loads(newtext)['translations'][0]['text']
  74.                     soup = soup.encode(formatter=UnsortedAttributes()).decode('utf-8')
  75.                     page = page.replace(new, soup)
  76.         if updated:
  77.             print(f'{filename} translated')
  78.             new_filename = f'{filename.split(".")[0]}_{destination_language}.html'
  79.             if use_translate_folder:
  80.                 try:
  81.                     with open(os.path.join(files_from_folder+r'\translated', new_filename), 'w', encoding='utf-8') as new_html:
  82.                         new_html.write(page)
  83.                 except:
  84.                     os.mkdir(files_from_folder+r'\translated')
  85.                     with open(os.path.join(files_from_folder+r'\translated', new_filename), 'w', encoding='utf-8') as new_html:
  86.                         new_html.write(page)
  87.             else:
  88.                 with open(os.path.join(files_from_folder, new_filename), 'w', encoding='utf-8') as html:
  89.                     html.write(page)
  90.  
Advertisement
Add Comment
Please, Sign In to add comment