The error message you're encountering suggests that there's a problem with the translation step, specifically with the response from the googletrans library. This often happens due to unexpected responses from the Google Translate service, possibly because of API changes, rate limits, or network issues. The googletrans library, especially the unofficial free version, can be unreliable due to these reasons.
Here's how you can address this issue:
Step 1: Update or Provide a Fallback
Google Translate’s free API (googletrans library) can be unreliable, leading to JSON parsing issues. Here, we'll implement a basic retry mechanism and also handle cases where translation might fail.
Step 2: Modify the Code
Here's an updated version of your script that includes better error handling for the translation step:
import os
import PyPDF2
from langdetect import detect
from googletrans import Translator
import time
def extract_text_from_pdf(pdf_path):
text_data = ""
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page_number in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_number]
text_data += page.extract_text()
return text_data
def translate_text(text, dest_language='en'):
translator = Translator()
try:
# Retry mechanism with limited attempts
for _ in range(3):
try:
translated = translator.translate(text, dest=dest_language)
return translated.text
except Exception as e:
print("Translation error:", e)
print("Retrying...")
time.sleep(2) # Wait before retrying
return "Translation failed." # Fallback message
except Exception as e:
print(f"Failed to translate. Error: {e}")
return text # Return the original text if translation fails
# Define the directory containing PDF files
data_folder = 'data'
output_folder = 'translated_texts'
# Ensure the output folder exists
os.makedirs(output_folder, exist_ok=True)
for pdf_file in os.listdir(data_folder):
if pdf_file.endswith('.pdf'):
pdf_path = os.path.join(data_folder, pdf_file)
text = extract_text_from_pdf(pdf_path)
if text:
# Detect language of the extracted text
try:
detected_lang = detect(text)
print(f"Detected Language for {pdf_file}: {detected_lang}")
except Exception as e:
print(f"Could not detect language for {pdf_file}. Error: {e}")
detected_lang = 'unknown'
# Translate text to English (or specify another language)
translated_text = translate_text(text, dest_language='en')
# Save the translated text
output_txt_file = os.path.join(output_folder, f"{os.path.splitext(pdf_file)[0]}_translated.txt")
with open(output_txt_file, 'w', encoding='utf-8') as f:
f.write(translated_text)
print(f"Translation complete for {pdf_file} and saved to {output_txt_file}")
Explanation:
-
Retry Mechanism: A simple retry mechanism has been added to attempt the translation up to three times before giving up. This can help with temporary network or service disruptions.
-
Error Handling: Additional try-except blocks catch and report errors more gracefully, providing fallback messages and ensuring that the script runs even if some operations fail.
-
Fallbacks and Delays: Adding a delay with time.sleep(2) between retries can help with rate-limiting issues.
Consider Alternative APIs:
For more reliable translation capabilities, consider using a paid service, such as the Google Cloud Translation API or other providers like DeepL, Microsoft Translator, or AWS Translate, which provide scalable and reliable translation services. Using these will likely require authentication and API key management but can offer more consistent performance.