Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- import weechat as w
- import json
- SCRIPT_NAME = "translate"
- SCRIPT_AUTHOR = "Jerzy Dabrowski (kofany) <j@dabrowski.biz>"
- SCRIPT_VERSION = "1.0"
- SCRIPT_LICENSE = "GPL"
- SCRIPT_DESC = "Translates messages for specified channels and servers using Google Translate API."
- TRANSLATE_API_URL = "https://translation.googleapis.com/language/translate/v2"
- DETECT_API_URL = "https://translation.googleapis.com/language/translate/v2/detect"
- settings = {
- "api_key": "",
- "translate_channels_in": "{}",
- "translate_channels_out": "{}",
- "no_translate_lang": "pl", # Default language not to translate
- }
- translated_texts = {}
- def debug_print(buffer, message):
- w.prnt(buffer, "DEBUG: " + message)
- def get_full_channel_name(channel, server):
- full_channel_name = "{}@{}".format(channel, server)
- debug_print("", f"[Translate Debug] Full channel name generated: {full_channel_name} from Channel: {channel}, Server: {server}")
- return full_channel_name
- def api_request_cb(data, url, request, response):
- debug_print("", f"[Translate Debug api_request_cb BEG] Current translated_texts content: {translated_texts}")
- # Debugowanie danych wejściowych
- debug_print("", "[Translate Debug] API request callback triggered.")
- debug_print("", f"[Translate Debug] Input data: {data}")
- debug_print("", f"[Translate Debug] URL: {url}")
- debug_print("", f"[Translate Debug] Request: {request}")
- debug_print("", f"[Translate Debug] Response: {response}")
- callback_data = json.loads(data)
- buffer = callback_data['buffer']
- action = callback_data['action']
- message_id = callback_data.get('message_id', '')
- text_to_translate = callback_data.get('text', '') # Pobieramy tekst bezpośrednio z danych callback
- debug_print("", f"[Translate Debug] Action: {action}")
- debug_print("", f"[Translate Debug] Callback data: {callback_data}")
- try:
- response_data = json.loads(response['output'])
- debug_print("", "[Translate Debug] Successfully parsed response data.")
- except Exception as e:
- debug_print(buffer, f"[Translate Debug] Error parsing response data: {e}")
- return w.WEECHAT_RC_ERROR
- if action == 'detect_and_translate':
- if 'data' in response_data and 'detections' in response_data['data']:
- detected_lang = response_data['data']['detections'][0][0]['language']
- debug_print(buffer, f"[Translate Debug] Detected language: {detected_lang}")
- target_lang = callback_data['target_lang']
- if detected_lang != target_lang:
- debug_print(buffer, "[Translate Debug] Detected language differs from target. Initiating translation.")
- if text_to_translate:
- # Wywołujemy funkcję translate z tekstem bezpośrednio
- translate(buffer, detected_lang, target_lang, callback_data['api_key'], 'translate', message_id, text_to_translate)
- else:
- debug_print(buffer, f"[Translate Debug] No text found for message ID: {message_id}. Skipping translation.")
- else:
- debug_print(buffer, "[Translate Debug] Detected language is the same as target. No translation needed.")
- else:
- debug_print(buffer, "Error in response: No detections found")
- elif action == 'translate':
- if 'data' in response_data and 'translations' in response_data['data']:
- translated_text = response_data['data']['translations'][0]['translatedText']
- translated_texts[message_id] = translated_text # Aktualizujemy słownik, jeśli potrzebujemy zachować przetłumaczony tekst
- debug_print(buffer, f"[Translate Debug] Translation completed: {translated_text}")
- else:
- debug_print(buffer, "Error in response: No translations found")
- debug_print("", f"[Translate Debug api_request_cb END] Current translated_texts content: {translated_texts}")
- return w.WEECHAT_RC_OK
- def translate(buffer, source_lang, target_lang, api_key, callback_action, message_id, text_to_translate):
- debug_print("", f"[Translate Debug translate BEG] Current translated_texts content: {translated_texts}")
- debug_print("", "[Translate Debug] Initiating translation process.")
- if text_to_translate:
- debug_print("", f"[Translate Debug] Text to translate (ID: {message_id}): {text_to_translate}")
- else:
- debug_print("", f"[Translate Debug] No text found for message ID: {message_id}. Skipping translation.")
- return
- debug_print("", f"[Translate Debug] Source language: {source_lang}, Target language: {target_lang}")
- debug_print("", f"[Translate Debug] API Key: {'Present' if api_key else 'Not Present'}")
- post_data = json.dumps({'q': text_to_translate, 'source': source_lang, 'target': target_lang, 'format': 'text'})
- headers = "Content-Type: application/json\nx-goog-api-key: " + api_key
- options = {"postfields": post_data, "httpheader": headers}
- callback_data = json.dumps({
- 'buffer': buffer,
- 'action': callback_action,
- 'api_key': api_key,
- 'target_lang': target_lang,
- 'message_id': message_id
- })
- debug_print("", "[Translate Debug] Prepared request data for translation.")
- debug_print("", f"[Translate Debug] Post data: {post_data}")
- debug_print("", f"[Translate Debug] Headers: {headers}")
- debug_print("", f"[Translate Debug] Callback data: {callback_data}")
- w.hook_url(TRANSLATE_API_URL, options, 20000, "api_request_cb", callback_data)
- debug_print("", "[Translate Debug] Hook URL called for translation.")
- debug_print("", f"[Translate Debug translate END] Current translated_texts content: {translated_texts}")
- def detect_language_and_translate(buffer, message_id, text, server, channel, target_lang, api_key):
- debug_print("", f"[Translate Debug detect_language_and_translate BEG] Current translated_texts content: {translated_texts}")
- debug_print("", "[Translate Debug] Starting language detection and translation process.")
- debug_print("", f"[Translate Debug] Text to detect and translate: {text}")
- debug_print("", f"[Translate Debug] Target language: {target_lang}")
- debug_print("", f"[Translate Debug] API Key: {'Present' if api_key else 'Not Present'}")
- # Zapisz tekst przed wywołaniem detekcji
- translated_texts[message_id] = text
- post_data = json.dumps({'q': text})
- headers = "Content-Type: application/json\nx-goog-api-key: " + api_key
- options = {"postfields": post_data, "httpheader": headers}
- callback_data = json.dumps({
- 'buffer': buffer,
- 'message_id': message_id,
- 'text': text,
- 'server': server,
- 'channel': channel,
- 'target_lang': target_lang,
- 'action': 'detect_and_translate',
- 'api_key': api_key
- })
- debug_print("", "[Translate Debug] Prepared request data for language detection and translation.")
- debug_print("", f"[Translate Debug] Post data: {post_data}")
- debug_print("", f"[Translate Debug] Headers: {headers}")
- debug_print("", f"[Translate Debug] Callback data: {callback_data}")
- w.hook_url(DETECT_API_URL, options, 20000, "api_request_cb", callback_data)
- debug_print("", "[Translate Debug] Hook URL called for language detection and translation.")
- debug_print("", f"[Translate Debug detect_language_and_translate END] Current translated_texts content: {translated_texts}")
- def translate_incoming_message_cb(data, modifier, modifier_data, string):
- debug_print("", f"[Translate Debug translate_incoming_message_cb BEG] Current translated_texts content: {translated_texts}")
- api_key = w.config_get_plugin("api_key")
- if not api_key:
- debug_print("", "[Translate Debug] API key is not set.")
- return string
- parsed_data = w.info_get_hashtable("irc_message_parse", {"message": string})
- channel = parsed_data["channel"]
- message = parsed_data["text"]
- server = modifier_data
- message_id = str(hash(message)) # Unique ID for the message
- debug_print("", f"[Translate Debug] Received message: {message}")
- debug_print("", f"[Translate Debug] Channel: {channel}, Server: {server}")
- debug_print("", f"[Translate Debug] Message ID: {message_id}")
- full_channel_name = get_full_channel_name(channel, server)
- translate_channels_in = json.loads(w.config_get_plugin("translate_channels_in"))
- debug_print("", f"[Translate Debug] Full channel name: {full_channel_name}")
- debug_print("", f"[Translate Debug] Translate channels in: {translate_channels_in}")
- if full_channel_name in translate_channels_in:
- target_lang = translate_channels_in[full_channel_name]
- debug_print("", f"[Translate Debug] Target language for translation: {target_lang}")
- translated_texts[message_id] = message # Store original message for translation
- detect_language_and_translate("", message_id, message, server, channel, target_lang, api_key)
- else:
- debug_print("", "[Translate Debug] Channel not in translate_channels_in list.")
- # Check if translated text is available and replace original message
- if message_id in translated_texts:
- translated_message = translated_texts.pop(message_id)
- debug_print("", f"[Translate Debug] Translated message: {translated_message}")
- return string.replace(message, translated_message)
- else:
- debug_print("", "[Translate Debug] Translated message not available yet.")
- debug_print("", f"[Translate Debug translate_incoming_message_cb BEG] Current translated_texts content: {translated_texts}")
- return string
- def translate_command_cb(data, buffer, args):
- argv = args.split(" ")
- command = argv[0] if len(argv) > 0 else ""
- if command == "list":
- translate_channels_in = json.loads(w.config_get_plugin("translate_channels_in"))
- translate_channels_out = json.loads(w.config_get_plugin("translate_channels_out"))
- w.prnt(buffer, "Channels for incoming translation:")
- for channel, lang in translate_channels_in.items():
- w.prnt(buffer, " {} -> {}".format(channel, lang))
- w.prnt(buffer, "Channels for outgoing translation:")
- for channel, lang in translate_channels_out.items():
- w.prnt(buffer, " {} -> {}".format(channel, lang))
- elif command in ["addin", "addout"]:
- if len(argv) != 4:
- w.prnt(buffer, "Usage: /translate addin|addout <server> <channel> <target_lang>")
- return w.WEECHAT_RC_ERROR
- server_channel = get_full_channel_name(argv[2], argv[1])
- target_lang = argv[3]
- translate_channels = json.loads(w.config_get_plugin("translate_channels_in" if command == "addin" else "translate_channels_out"))
- translate_channels[server_channel] = target_lang
- w.config_set_plugin("translate_channels_in" if command == "addin" else "translate_channels_out", json.dumps(translate_channels))
- w.prnt(buffer, "{} added for {} translation to {}.".format(server_channel, "incoming" if command == "addin" else "outgoing", target_lang))
- elif command in ["delin", "delout"]:
- if len(argv) != 3:
- w.prnt(buffer, "Usage: /translate delin|delout <server> <channel>")
- return w.WEECHAT_RC_ERROR
- server_channel = get_full_channel_name(argv[2], argv[1])
- translate_channels = json.loads(w.config_get_plugin("translate_channels_in" if command == "delin" else "translate_channels_out"))
- if server_channel in translate_channels:
- del translate_channels[server_channel]
- w.config_set_plugin("translate_channels_in" if command == "delin" else "translate_channels_out", json.dumps(translate_channels))
- w.prnt(buffer, "{} removed from {} translation.".format(server_channel, "incoming" if command == "delin" else "outgoing"))
- else:
- w.prnt(buffer, "{} not found in {} translation settings.".format(server_channel, "incoming" if command == "delin" else "outgoing"))
- elif command == "code":
- magenta = w.color("magenta")
- reset = w.color("reset")
- codes = [
- ("Azerbaijani", "az"), ("Hausa", "ha"), ("Malay", "ms"), ("Spanish", "es"),
- ("Bambara", "bm"), ("Hawaiian", "haw"), ("Malayalam", "ml"), ("Sundanese", "su"),
- ("Basque", "eu"), ("Hebrew", "he"), ("Maltese", "mt"), ("Swahili", "sw"),
- ("Belarusian", "be"), ("Hindi", "hi"), ("Maori", "mi"), ("Swedish", "sv"),
- ("Bengali", "bn"), ("Hmong", "hmn"), ("Marathi", "mr"), ("Tagalog", "tl"),
- ("Bhojpuri", "bho"), ("Hungarian", "hu"), ("Meiteilon", "mni"), ("Tajik", "tg"),
- ("Bosnian", "bs"), ("Icelandic", "is"), ("Mizo (lus)", "lus"), ("Tamil", "ta"),
- ("Bulgarian", "bg"), ("Igbo", "ig"), ("Mongolian", "mn"), ("Tatar", "tt"),
- ("Catalan", "ca"), ("Ilocano (ilo)", "ilo"), ("Myanmar (my)", "my"), ("Telugu", "te"),
- ("Cebuano", "ceb"), ("Indonesian", "id"), ("Nepali", "ne"), ("Thai", "th"),
- ("Chinese (Simpl)", "zh-CN"), ("Irish", "ga"), ("Norwegian", "no"), ("Tigrinya", "ti"),
- ("Chinese (Trad)", "zh-TW"), ("Italian", "it"), ("Nyanja (ny)", "ny"), ("Tsonga", "ts"),
- ("Corsican", "co"), ("Japanese", "ja"), ("Odia (or)", "or"), ("Turkish", "tr"),
- ("Croatian", "hr"), ("Javanese", "jv"), ("Oromo (om)", "om"), ("Turkmen", "tk"),
- ("Czech", "cs"), ("Kannada", "kn"), ("Pashto", "ps"), ("Twi (ak)", "ak"),
- ("Danish", "da"), ("Kazakh", "kk"), ("Persian", "fa"), ("Ukrainian", "uk"),
- ("Dhivehi", "dv"), ("Khmer", "km"), ("Polish", "pl"), ("Urdu", "ur"),
- ("Dogri (doi)", "doi"), ("Kinyarwanda", "rw"), ("Portuguese", "pt"), ("Uyghur", "ug"),
- ("Dutch", "nl"), ("Konkani (gom)", "gom"), ("Punjabi", "pa"), ("Uzbek", "uz"),
- ("English", "en"), ("Korean", "ko"), ("Quechua", "qu"), ("Vietnamese", "vi"),
- ("Esperanto", "eo"), ("Krio (kri)", "kri"), ("Romanian", "ro"), ("Welsh", "cy"),
- ("Estonian", "et"), ("Kurdish", "ku"), ("Russian", "ru"), ("Xhosa", "xh"),
- ("Ewe", "ee"), ("Kurdish (ckb)", "ckb"), ("Samoan", "sm"), ("Yiddish", "yi"),
- ("Filipino", "fil"), ("Kyrgyz", "ky"), ("Sanskrit", "sa"), ("Yoruba", "yo"),
- ("Finnish", "fi"), ("Lao", "lo"), ("Scots (gd)", "gd"), ("Zulu", "zu"),
- ("French", "fr"), ("Latin", "la"), ("Sepedi (nso)", "nso"),
- ("Frisian", "fy"), ("Latvian", "lv"), ("Serbian", "sr"),
- ]
- w.prnt("", "Available language codes:")
- column_width = 20
- for i in range(0, len(codes), 4):
- line = "".join(f"{name.ljust(column_width - len(code))}{magenta}{code}{reset} " for name, code in codes[i:i+4])
- w.prnt(buffer, line)
- elif command == "help":
- w.prnt(buffer, "/translate command usage:")
- w.prnt(buffer, "/translate list - Show all channels with translation settings")
- w.prnt(buffer, "/translate addin <server> <channel> <target_lang> - Add a channel to translate incoming messages")
- w.prnt(buffer, "/translate addout <server> <channel> <target_lang> - Add a channel to translate outgoing messages")
- w.prnt(buffer, "/translate delin <server> <channel> - Remove a channel from translating incoming messages")
- w.prnt(buffer, "/translate delout <server> <channel> - Remove a channel from translating outgoing messages")
- w.prnt(buffer, "/translate code - Show available language codes for translation")
- w.prnt(buffer, "/translate help - Show this help message")
- else:
- w.prnt(buffer, "Unknown command. Use /translate help for usage information.")
- return w.WEECHAT_RC_OK
- if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
- for option, default_value in settings.items():
- if not w.config_is_set_plugin(option):
- w.config_set_plugin(option, default_value)
- w.hook_modifier("irc_in_privmsg", "translate_incoming_message_cb", "")
- w.hook_command("translate", "Manage translation settings",
- "list | addin <server> <channel> <target_lang> | addout <server> <channel> <target_lang> | delin <server> <channel> | delout <server> <channel> | code | help",
- "list: show all channels with translation settings\n"
- "addin: add a channel to translate incoming messages\n"
- "addout: add a channel to translate outgoing messages\n"
- "delin: remove a channel from translating incoming messages\n"
- "delout: remove a channel from translating outgoing messages\n"
- "code: show available language codes for translation\n"
- "help: show help information for the /translate command\n",
- "list || addin %(irc_servers) %(irc_channels) || addout %(irc_servers) %(irc_channels) || delin %(irc_servers) %(irc_channels) || delout %(irc_servers) %(irc_channels) || code || help",
- "translate_command_cb", "")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement