nicuf

translate html webpages

Jan 4th, 2024 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.06 KB | None | 0 0
  1. import os
  2. import re
  3. import textwrap
  4. import regex as re
  5. import regex
  6. import time
  7. from deep_translator import GoogleTranslator
  8. from deep_translator.exceptions import RequestError  # Import specific exceptions
  9.  
  10. from dotenv import load_dotenv  # Import the dotenv module
  11.  
  12.  
  13. # Load environment variables from .env file
  14. load_dotenv()
  15.  
  16. # Initialize the Deep Translator Translator
  17. translator = GoogleTranslator(source='auto', target='ro')
  18.  
  19. # Initialize a counter for the translated files
  20. translated_files_count = 0
  21.  
  22. import os
  23.  
  24. # Folder path containing the HTML files
  25. folder_path = r"c:\\Folder-Oana\\extracted\\"
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35. # Dimensiunea minimă a fișierului în kilobytes (1.3 KB)
  36. min_file_size_kb = 1.3
  37.  
  38. # Parcurgeți toate fișierele din director
  39. for filename in os.listdir(folder_path):
  40.     file_path = os.path.join(folder_path, filename)
  41.  
  42.     # Verificați dacă este un fișier și obțineți dimensiunea sa
  43.     if os.path.isfile(file_path):
  44.         file_size_kb = os.path.getsize(file_path) / 1024  # Dimensiunea fișierului în KB
  45.  
  46.         # Dacă fișierul este mai mic decât dimensiunea minimă, ștergeți-l
  47.         if file_size_kb < min_file_size_kb:
  48.             print(f"Șterg fișierul {filename} deoarece este mai mic decât 1.3 KB.")
  49.             os.remove(file_path)
  50.  
  51.  
  52. # Regexuri inainte de traducerea fisierului
  53. regex = r"<p>(.{0,9})<\/p>"
  54.  
  55.  
  56.  
  57. def add_paragraph_tags(text):
  58.     new_lines = []
  59.     for line in text.split('\n'):
  60.         stripped_line = line.strip()
  61.  
  62.         # Săriți peste linii care conțin taguri specifice
  63.         if re.search(r'(<title>.*?</title>|<meta name="description" content=".*?"|<link rel="canonical" href=".*?"|<p class="pl-3 pt-3">.*?</a></p>)', stripped_line):
  64.             new_line = line
  65.         elif stripped_line and not stripped_line.startswith('<p>') and not stripped_line.endswith('</p>'):
  66.             new_line = f'<p>{stripped_line}</p>'
  67.         else:
  68.             new_line = line
  69.         new_lines.append(new_line)
  70.     return '\n'.join(new_lines)
  71.  
  72. # Parcurgeți fiecare fișier HTML și aplicați funcția
  73. for filename in os.listdir(folder_path):
  74.     if filename.endswith((".html", ".htm")):
  75.         filepath = os.path.join(folder_path, filename)
  76.         with open(filepath, 'r', encoding='utf-8') as file:
  77.             html_content = file.read()
  78.         # Aplicați funcția de adăugare a tagurilor <p>
  79.         updated_html_content = add_paragraph_tags(html_content)
  80.         # Rescrieți fișierul cu conținutul actualizat
  81.         with open(filepath, 'w', encoding='utf-8') as file:
  82.             file.write(updated_html_content)
  83.  
  84.  
  85.  
  86.  
  87. # Iterate through all HTML files in the folder
  88. for filename in os.listdir(folder_path):
  89.   if filename.endswith((".html", ".htm")):
  90.     filepath = os.path.join(folder_path, filename)
  91.  
  92.     # Read the HTML file content with UTF-8 encoding
  93.     with open(filepath, "r", encoding="utf-8") as f:
  94.         html_content = f.read()
  95.  
  96.  
  97.  
  98.  
  99.     # Remove escaped characters
  100.     html_content = re.sub(r"\\\\.*$", "", html_content)
  101.  
  102.     # html_content = re.sub(r"^(?!<p>|</p>)(.*)(<\/p>)$", "<p>\1\2", html_content)
  103.     # html_content = re.sub(r"(^(?!<p>))(.*)(</p>)", "\1\2", html_content)
  104.     # html_content = re.sub(r"^(?!<p>)(.*)(<\/p>)$", "<p>\1\2", html_content)
  105.  
  106.  
  107.  
  108.     # Format paragraphs
  109.     html_content = re.sub(r"^(.*?)$", r"<p>\1</p>", html_content, flags=re.MULTILINE)
  110.  
  111.  
  112.     # Remove paragraphs with less than 10 words (multi-line)
  113.     html_content = re.sub(r"<p>.{0,9}<\/p>", "", html_content, flags=re.MULTILINE)
  114.  
  115.  
  116.     # Remove leading > from the first paragraph
  117.     html_content = re.sub(r"^>", "", html_content)
  118.  
  119.     # Remove U+200B non-breaking space (hair space)
  120.     html_content = re.sub(r"\x200B", "", html_content)
  121.     html_content = re.sub(r"\u00C2", "", html_content)
  122.     html_content = re.sub(r"\u001C", "", html_content) #  NSBN
  123.     html_content = re.sub(r"<p>\d+</p>", "", html_content)
  124.  
  125.  
  126.         # Adaugă o linie nouă după fiecare tag </p>
  127.     html_content = re.sub(r'</p>', '</p>\n', html_content)
  128.  
  129.         # Adaugă un tag <p> la începutul liniilor care nu încep cu un tag HTML
  130.     # html_content = re.sub(r'(^)((?!<[^>]+>).*$)', r'\1<p>\2</p>', html_content, flags=re.MULTILINE)
  131.  
  132.     # html_content = re.sub(r'^(?!.*<.*>)(.*)$', r'<p>\1</p>', html_content, flags=re.MULTILINE)
  133.  
  134.         # Convertește fiecare pereche de taguri <p> adiacente într-un singur tag <p>
  135.     # html_content = re.sub(r'((?<=).*?</p>)(<p>(?=.*))', '\1\n\2', html_content, flags=re.MULTILINE)
  136.  
  137.  
  138.     html_content = re.sub(r'^\s', '', html_content, flags=re.MULTILINE)
  139.     # html_content = re.sub(r'</p></p>', '</p>', html_content, flags=re.MULTILINE)
  140.  
  141.  
  142.  
  143.     html_content = re.sub(r'<[^>]*>(?:\s*\w+\s*){1,3}\s*<\/[^>]*>', '', html_content) # sterge tagurile care contin mai putin de 4 cuvinte
  144.     html_content = re.sub(r'<p><title>', '<title>', html_content)
  145.     html_content = re.sub(r'<p></p>', '', html_content)
  146.     html_content = re.sub(r'</title></p>', '</title>', html_content)
  147.     html_content = re.sub(r'<p><meta name=', '<meta name=', html_content)
  148.     html_content = re.sub(r'"/></p>', '"/>', html_content)
  149.     html_content = re.sub(r'<p><p>', '<p>', html_content, flags=re.MULTILINE)
  150.     html_content = re.sub(r'</p></p>', '</p>', html_content, flags=re.MULTILINE)
  151.     html_content = re.sub(r'^</p>$', '', html_content, flags=re.MULTILINE) #sterge orice <p> gol de la inceputul linilor
  152.     html_content = re.sub(r'<p style=".*?">', '<p>', html_content, flags=re.MULTILINE)
  153.     html_content = re.sub(r'<font.*?">', '', html_content, flags=re.MULTILINE)
  154.     html_content = re.sub(r'</font>', '', html_content, flags=re.MULTILINE)
  155.     html_content = re.sub(r'"\/"', '"', html_content, flags=re.MULTILINE)
  156.     html_content = re.sub(r'<strong>|</strong>', ' ', html_content, flags=re.MULTILINE)
  157.     html_content = re.sub(r'<p>\d+</p>', '', html_content, flags=re.MULTILINE)
  158.     html_content = re.sub(r'‘|’', '', html_content, flags=re.MULTILINE)
  159.     html_content = re.sub(r'”|“', '', html_content, flags=re.MULTILINE)
  160.  
  161.  
  162.  
  163.  
  164.     # html_content = re.sub(r'^(?=(\w+\s*){5,}).*$', '<p>$0</p>', html_content, flags=re.MULTILINE)  # adauga  <p>帮助你定期反馈,同时
  165.     # html_content = re.sub(r'(<p>.*?)(?<!</p>)$', '\1</p>', html_content, flags=re.MULTILINE)
  166.  
  167.     # Write the modified HTML file content
  168.     # Read the HTML file content with UTF-8 encoding
  169.     with open(filepath, "r", encoding="utf-8") as f:
  170.         html_content = f.read()
  171.  
  172.  
  173.  
  174.  
  175.  
  176.  
  177.  
  178. # Sortează fișierele alfabetic
  179. sorted_files = sorted(os.listdir(folder_path))
  180.  
  181.  
  182.  
  183.  
  184. # HTML tags to translate
  185. tags_to_translate = [
  186.     r'(<title>)(.*?)(<\/title>)',
  187.     r'(<meta name="description" content=")(.*?)(>)',
  188.     r'(<div class="sc-jKDlA-D hSgfYV sc-glENfF hIVUeB">)(.*?)(<\/div>)',
  189.     r'(<p>)(.*?)(<\/p>)',
  190.     r'(<h4 class="sc-jMKfon fhunKk">)(.*?)(<\/h4>)',
  191.     r'(<h2">)([\s\S]*?)(<\/h2>)'
  192.  
  193.     # ... alte tag-uri, structurate similar
  194. ]
  195.  
  196. def translate_in_parts(text, translator, max_length=4800, max_retries=5):
  197.     """Traduce textul în fragmente pentru a evita limita de caractere a API-ului."""
  198.     translated = ''
  199.     while text:
  200.         # Luăm un fragment de text pentru a rămâne sub limita de 5000 de caractere
  201.         part = text[:max_length]
  202.         text = text[max_length:]
  203.  
  204.         attempt = 0
  205.         while attempt < max_retries:
  206.             try:
  207.                 translated_part = translator.translate(part)
  208.                 translated += translated_part
  209.                 break  # Break the loop if translation is successful
  210.             except RequestError:  # Use the imported exception
  211.                 attempt += 1
  212.                 time.sleep(1)  # Așteaptă un pic înainte de a reîncerca
  213.                 print(f"Reîncercarea {attempt} pentru fragmentul: {part[:30]}...")
  214.     return translated
  215.  
  216. translated_tags_count = 0  # Inițializează contorul pentru tagurile traduse
  217.  
  218.  
  219.  
  220.  
  221.  
  222. import unidecode
  223.  
  224. def format_title_for_canonical(title):
  225.     # Elimină tot ce este după primul semn "-" și formatează pentru tag-ul canonical
  226.     title = re.split(r' - ', title, maxsplit=1)[0]
  227.     title = title.lower()
  228.     title = unidecode.unidecode(title)
  229.     title = re.sub(r'\s+', '-', title)
  230.     return title
  231.  
  232. def format_title_for_title_tag(title):
  233.     # Elimină tot ce este după primul semn "-" pentru tag-ul <title>
  234.     title = re.split(r' - ', title, maxsplit=1)[0]
  235.     return title
  236.  
  237.  
  238.  
  239. for filename in sorted_files:
  240.     if filename.endswith((".html", ".htm")):
  241.         print(f"Procesez fișierul: {filename}")
  242.         file_path = os.path.join(folder_path, filename)
  243.  
  244.         file_size_kb = os.path.getsize(file_path) / 1024
  245.         if file_size_kb < min_file_size_kb:
  246.             print(f"Șterg fișierul {filename} deoarece este mai mic decât 1.3 KB.")
  247.             os.remove(file_path)
  248.             continue
  249.  
  250.         with open(file_path, 'rb') as file:
  251.             try:
  252.                 html_content = file.read().decode('utf-8')
  253.             except UnicodeDecodeError:
  254.                 # Încercați alte seturi de caractere, cum ar fi 'ISO-8859-1' sau 'latin-1'
  255.                 html_content = file.read().decode('ISO-8859-1')
  256.  
  257.  
  258.         try:
  259.             title_match = re.search(r'<title>(.*?)<\/title>', html_content)
  260.             if title_match:
  261.                 title_content = title_match.group(1)
  262.                 formatted_title_for_title_tag = format_title_for_title_tag(title_content)
  263.                 formatted_title_for_canonical = format_title_for_canonical(title_content)
  264.  
  265.                 # Înlocuirea sigură a tagurilor
  266.                 html_content = html_content.replace(title_match.group(0), f'<title>{formatted_title_for_title_tag}</title>')
  267.                 canonical_tag = f'<link rel="canonical" href="{formatted_title_for_canonical}.html" />'
  268.                 html_content = re.sub(r'<link rel="canonical" href=".*?" \/>', canonical_tag, html_content)
  269.         except Exception as e:
  270.             print(f"Eroare la procesarea fișierului {filename}: {e}")
  271.             continue
  272.  
  273.  
  274.  
  275.  
  276.  
  277.                           # Elimină caracterele ZWSP
  278.             html_content = remove_zwsp(html_content)
  279.  
  280.  
  281.             html_content = re.sub(r'<p></p>', '', html_content, flags=re.MULTILINE)
  282.             html_content = re.sub(r'<p>\d+</p>', '', html_content, flags=re.MULTILINE)
  283.  
  284.  
  285.  
  286.             '''
  287.            def add_paragraph_tags(text):
  288.                return regex.sub(r'^(?=(\w+\s*){5,}).*$', '<p>$0</p>', text, flags=regex.MULTILINE)
  289.  
  290.            # Aplicați funcția la conținutul HTML
  291.            html_content = add_paragraph_tags(html_content)
  292.            '''
  293.  
  294.  
  295.  
  296.  
  297.         for tag in tags_to_translate:
  298.             matches = re.finditer(tag, html_content, re.DOTALL)
  299.  
  300.             match_index = 0  # Adaugă această linie pentru a declara variabila match_index înainte de buclă
  301.  
  302.             for match in matches:
  303.                 match_index += 1  # Modificare pentru a incrementa match_index
  304.  
  305.                 full_match = match.group(0)
  306.                 tag_start = match.group(1)
  307.                 tag_content = match.group(2)
  308.                 tag_end = match.group(3)
  309.  
  310.                 print(f"Traduc tagul {match_index}: {tag_start}...{tag_end}")
  311.                 # print(f"Traduc tagul {tag_content}")
  312.  
  313.                 translated_content = translate_in_parts(tag_content, translator)
  314.                 translated_tag = f"{tag_start}{translated_content}{tag_end}"
  315.  
  316.                 html_content = html_content.replace(full_match, translated_tag)
  317.  
  318.                 translated_tags_count += 1  # Increment contorul de taguri traduse
  319.  
  320.  
  321.  
  322.  
  323.         new_filename = f"{filename.split('.')[0]}_ro.html"
  324.         translated_folder_path = os.path.join(folder_path, 'translated')
  325.  
  326.         if not os.path.exists(translated_folder_path):
  327.             os.mkdir(translated_folder_path)
  328.  
  329.         with open(os.path.join(translated_folder_path, new_filename), 'w', encoding='utf-8') as file:
  330.             file.write(html_content)
  331.  
  332.         translated_files_count += 1
  333.         print(f"Fișierul a fost tradus și salvat: {new_filename}")
  334.  
  335. print("Toate fișierele au fost traduse.")
  336.  
Add Comment
Please, Sign In to add comment