Skip to content

Commit

Permalink
Improve the details of the app
Browse files Browse the repository at this point in the history
  • Loading branch information
seratch committed Apr 4, 2022
1 parent 647621e commit 829c324
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 22 deletions.
60 changes: 49 additions & 11 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 2,11 @@
import logging
import os
import time
from typing import Optional

import deepl
import requests
from deepl import DocumentHandle
from slack_bolt import App, Say, BoltContext, Ack
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk import WebClient
Expand Down Expand Up @@ -105,7 107,11 @@ def handle_some_action(ack: Ack):

@app.event("reaction_added")
def handle_reaction_added_events(
event: dict, say: Say, client: WebClient, logger: logging.Logger
event: dict,
context: BoltContext,
say: Say,
client: WebClient,
logger: logging.Logger,
):
item = event.get("item", {})
if item.get("type") != "message":
Expand All @@ -115,11 121,17 @@ def handle_reaction_added_events(
if channel is None or ts is None:
logger.debug("Skipped because either channel or ts is missing")
return
lang = detect_lang(event)
reaction_name: str = event.get("reaction")
lang = detect_lang(reaction_name)
if lang is None:
logger.debug(
f"Skipped because no lang detected from the reaction ({event.get('reaction')})"
)
if reaction_name.startswith("flag-"):
say(
thread_ts=ts,
text=f"Hey <@{context.user_id}>, the language used in {reaction_name} is not yet supported.",
)
return
replies = client.conversations_replies(
channel=channel,
Expand Down Expand Up @@ -150,7 162,7 @@ def handle_reaction_added_events(

already_translated = False
for message in replies.get("messages"):
# check if the translated file is already uploaded
# Check if the translated file is already uploaded
if (
message.get("files") is not None
and message.get("files")[0].get("name") == translated_file_name
Expand All @@ -164,17 176,38 @@ def handle_reaction_added_events(
if already_translated:
continue

# call DeepL API
# Download the Slack file content
input_document = requests.get(
url=file.get("url_private_download"),
headers={"Authorization": f"Bearer {client.token}"},
).content
# The IO object to save the result file data returned from DeepL
output_document = io.BytesIO()

# Calling DeepL API
try:
handle = translator.translate_document_upload(
input_document,
target_lang=lang.upper(),
filename=translated_file_name,
handle: Optional[DocumentHandle] = None
try:
handle = translator.translate_document_upload(
input_document,
target_lang=lang.upper(),
filename=translated_file_name,
)
except Exception as e:
say(
thread_ts=ts,
text=f"Hey <@{context.user_id}>, we failed to translate the document "
f"into the language used in :{reaction_name}:. "
f"(file: {original_name}, lang: {lang}, error: ${e})",
)
return

say(
thread_ts=thread_ts,
text=f"Hey <@{context.user_id}>, "
f"thanks for requesting :{reaction_name}: (lang: {lang}) translation of `{original_name}`! "
"The DeepL backend is now working on the task :man-biking: "
"We will post a translated file once the translation is done! :bow:",
)

try:
Expand All @@ -190,14 223,18 @@ def handle_reaction_added_events(
except Exception as e:
say(
thread_ts=thread_ts,
text=f"Failed to translate the document (error: {e})",
text=":x: Failed to translate the document "
f"(file: {original_name}, reaction: :{reaction_name}:, lang: {lang}, error: {e})",
)
return

if not status.ok:
say(
thread_ts=thread_ts,
text=f"Failed to translate the document for some reason",
# TODO: improve this message to have the error details (need to enhance the DeepL SDK)
text=":x: Failed to translate the document for some reason. "
"The common pattern is that the original document is already written in the target language. "
f"(file: {original_name}, reaction: :{reaction_name}:, lang: {lang})",
)
return

Expand All @@ -208,7 245,8 @@ def handle_reaction_added_events(
file=output_document,
channels=[channel],
thread_ts=thread_ts,
initial_comment=f"Here is the {lang} translation of {original_name} :wave:",
initial_comment=f"Hey <@{context.user_id}>, thanks for waiting!"
f"Here is :{reaction_name}: (lang: {lang}) translation of `{original_name}` :white_check_mark:",
)
finally:
output_document.close()
Expand Down
23 changes: 13 additions & 10 deletions languages.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 5,7 @@
"ac": "en-us",
"ag": "en-us",
"ai": "en-us",
"ao": "pt",
"ao": "pt-pt",
"ar": "es",
"as": "en-us",
"at": "de",
Expand All @@ -20,7 20,7 @@
"bn": "en-us",
"bo": "es",
"bq": "nl",
"br": "pt",
"br": "pt-br",
"bs": "en-us",
"bw": "en-us",
"bz": "en-us",
Expand All @@ -38,7 38,7 @@
"cp": "fr",
"cr": "es",
"cu": "es",
"cv": "pt",
"cv": "pt-pt",
"cw": "nl",
"cx": "en-us",
"de": "de",
Expand All @@ -47,6 47,7 @@
"do": "es",
"ea": "es",
"ec": "es",
"england": "en-gb",
"es": "es",
"fj": "en-us",
"fk": "en-us",
Expand All @@ -66,10 67,11 @@
"gs": "en-us",
"gt": "es",
"gu": "en-us",
"gw": "pt",
"gw": "pt-pt",
"gy": "en-us",
"hn": "es",
"ic": "es",
"ie": "en-gb",
"im": "en-us",
"io": "en-us",
"it": "it",
Expand All @@ -91,7 93,7 @@
"mu": "en-us",
"mw": "en-us",
"mx": "es",
"mz": "pt",
"mz": "pt-pt",
"na": "en-us",
"nc": "fr",
"ne": "fr",
Expand All @@ -107,21 109,22 @@
"pm": "fr",
"pn": "en-us",
"pr": "es",
"pt": "pt",
"pt-pt": "pt-pt",
"pw": "en-us",
"py": "es",
"re": "fr",
"ru": "ru",
"sb": "en-us",
"sc": "en-us",
"scotland": "en-gb",
"sg": "en-us",
"sh": "en-us",
"sl": "en-us",
"sm": "it",
"sn": "fr",
"sr": "nl",
"ss": "en-us",
"st": "pt",
"st": "pt-pt",
"sv": "es",
"sx": "nl",
"ta": "en-us",
Expand All @@ -140,15 143,15 @@
"vg": "en-us",
"vi": "en-us",
"wf": "fr",
"wales": "en-gb",
"yt": "fr",
"zm": "en-us",
"zw": "en-us",
}


def detect_lang(event: dict) -> Optional[str]:
reaction_name = event.get("reaction")
m = re.findall("/(?!flag-\b)\b\\w /", reaction_name)
def detect_lang(reaction_name: str) -> Optional[str]:
m = re.findall(r"flag-(\w )", reaction_name)
if m is not None and m != []:
country = m[0]
return reaction_to_lang.get(country)
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 13,7 @@ This app provides two features as below.
When a user adds a reaction to a message with files, this app calls [DeepL's document translation API](https://www.deepl.com/docs-api/translating-documents/).
When the translation is done, this app uploads the result as a new file in the message's thread.

<img width="500" src="https://user-images.githubusercontent.com/19658/161419367-c1b48d85-5bf7-4199-8857-66e5649f838a.png">
<img width="500" src="https://user-images.githubusercontent.com/19658/161464009-fc530afc-36bb-4eb8-a491-98dbb6389552.png">

### Usage Dashboard

Expand Down

0 comments on commit 829c324

Please sign in to comment.