Skip to content

Instantly share code, notes, and snippets.

@scillidan
Last active January 25, 2025 08:13
Show Gist options
  • Save scillidan/26d935cb62964462351c392e78d91077 to your computer and use it in GitHub Desktop.
Save scillidan/26d935cb62964462351c392e78d91077 to your computer and use it in GitHub Desktop.
# Refer to https://deeplx.owo.network/integration/python.html
# Write by GPT-4o mini 👨‍💻, scillidan 🤡
# How to use
# Run deeplx
# pip install httpx langid
# python this.py <Input> <SourceLanguage> <TargetLanguage>
import argparse
import httpx
import json
import langid
def escape_special_characters(text):
"""Escape special characters that affect command operations."""
return text.replace('"', '\\"').replace("'", "\\'").replace("\n", "\\n")
def format_translations(response):
"""Format the response from the API to display translations."""
response_data = json.loads(response)
alternatives = response_data.get("alternatives", [])
data = response_data.get("data", "")
# Initialize translations list
translations = []
# Add the main translation if it's available
if data:
translations.append(data)
# Add alternatives if they are available
if isinstance(alternatives, list):
translations.extend(alternatives)
return translations
def main():
parser = argparse.ArgumentParser(description='Translate text using Deeplx API.')
parser.add_argument('input_text', type=str, help='Text to be translated')
parser.add_argument('source_language', type=str, nargs='?', default=None, help='Source language code (optional)')
parser.add_argument('target_language', type=str, help='Target language code')
parser.add_argument('--debug', action='store_true', help='Show debug information')
args = parser.parse_args()
if args.source_language is None:
detected_lang, _ = langid.classify(args.input_text)
args.source_language = detected_lang
# Escape special characters in the input text
formatted_input = escape_special_characters(args.input_text)
deeplx_api = "http://127.0.0.1:1188/translate"
data = {
"text": formatted_input,
"source_lang": args.source_language,
"target_lang": args.target_language
}
post_data = json.dumps(data)
if args.debug:
print(f"Request Data: {post_data}")
try:
response = httpx.post(url=deeplx_api, data=post_data)
response.raise_for_status()
translation_response = response.text
if args.debug:
print(f"Response: {translation_response}")
# Format and print the translations
translations = format_translations(translation_response)
# Hidden input
# print(formatted_input)
for translation in translations:
print(translation)
print() # Print an extra newline for better readability
except httpx.HTTPStatusError as e:
if args.debug:
print(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
else:
print("An error occurred during translation.")
except json.JSONDecodeError:
print("Failed to decode the response. Please ensure the API is returning valid JSON.")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment