from bs4 import BeautifulSoup from langdetect import detect, DetectorFactory import re import os # Set seed for consistent language detection results DetectorFactory.seed = 0 def extract_text_from_html(html_content): """Extracts visible text from HTML content.""" soup = BeautifulSoup(html_content, 'html.parser') # Remove script and style elements for script in soup(['script', 'style']): script.decompose() # Get text and clean up whitespace text = soup.get_text(separator=' ') text = re.sub(r'\s+', ' ', text).strip() return text def detect_language(text): """Detects the language of a given text.""" try: return detect(text) except: return "unknown" def analyze_email_with_subject(html_file_path: str, subject: str): """Reads HTML template from file, combines with subject, and detects language.""" # Read HTML content from file with open(html_file_path, 'r', encoding='utf-8') as file: html_content = file.read() # Extract text from HTML html_text = extract_text_from_html(html_content) # Combine subject and body text combined_text = subject.strip() + " " + html_text # Detect language of the combined text language = detect_language(combined_text) return language # 🔽 Example usage: if __name__ == "__main__": fr_subject = "À BIENTÔT FRANCE⭐️" # en_subject = "SEE YOU SOON SWEDEN⭐️⭐️⭐️" html_file = os.path.join(os.path.dirname(__file__), 'tate_mcrae_french_template.html') detected_language = analyze_email_with_subject(html_file, fr_subject) print("Detected language of email content and subject:", detected_language) "CA": { "default": { "name": "Sony Music Entertainment Canada Inc.", "address": "99 Atlantic Avenue, Suite 800, Toronto, Ontario, M6K 3J8" }, "fr": { "name": "Sony Music Entertainment Canada Inc.", "address": "99 avenue Atlantic, bureau 800, Toronto, Ontario, M6K 3J" } }