Skip to content

Commit 6cb631f

Browse files
committed
Added (smart) translation api
1 parent 8a53174 commit 6cb631f

File tree

2 files changed

+80
-3
lines changed

2 files changed

+80
-3
lines changed

scratchattach/other/other_apis.py

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,94 @@
11
"""Other Scratch API-related functions"""
22

3+
import json
4+
import warnings
5+
36
from ..utils import commons
7+
from ..utils.exceptions import BadRequest
48
from ..utils.requests import Requests as requests
5-
import json
9+
from ..utils.supportedlangs import SUPPORTED_CODES, SUPPORTED_NAMES
10+
611

712
# --- Front page ---
813

914
def get_news(*, limit=10, offset=0):
10-
return commons.api_iterative("https://api.scratch.mit.edu/news", limit = limit, offset = offset)
15+
return commons.api_iterative("https://api.scratch.mit.edu/news", limit=limit, offset=offset)
16+
1117

1218
def featured_data():
1319
return requests.get("https://api.scratch.mit.edu/proxy/featured").json()
1420

21+
1522
def featured_projects():
1623
return featured_data()["community_featured_projects"]
1724

25+
1826
def featured_studios():
1927
return featured_data()["community_featured_studios"]
2028

29+
2130
def top_loved():
2231
return featured_data()["community_most_loved_projects"]
2332

33+
2434
def top_remixed():
2535
return featured_data()["community_most_remixed_projects"]
2636

37+
2738
def newest_projects():
2839
return featured_data()["community_newest_projects"]
2940

41+
3042
def curated_projects():
3143
return featured_data()["curator_top_projects"]
3244

45+
3346
def design_studio_projects():
3447
return featured_data()["scratch_design_studio"]
3548

49+
3650
# --- Statistics ---
3751

3852
def total_site_stats():
3953
data = requests.get("https://scratch.mit.edu/statistics/data/daily/").json()
4054
data.pop("_TS")
4155
return data
4256

57+
4358
def monthly_site_traffic():
4459
data = requests.get("https://scratch.mit.edu/statistics/data/monthly-ga/").json()
4560
data.pop("_TS")
4661
return data
4762

63+
4864
def country_counts():
4965
return requests.get("https://scratch.mit.edu/statistics/data/monthly/").json()["country_distribution"]
5066

67+
5168
def age_distribution():
5269
data = requests.get("https://scratch.mit.edu/statistics/data/monthly/").json()["age_distribution_data"][0]["values"]
5370
return_data = {}
5471
for value in data:
5572
return_data[value["x"]] = value["y"]
5673
return return_data
5774

75+
5876
def monthly_comment_activity():
5977
return requests.get("https://scratch.mit.edu/statistics/data/monthly/").json()["comment_data"]
6078

79+
6180
def monthly_project_shares():
6281
return requests.get("https://scratch.mit.edu/statistics/data/monthly/").json()["project_data"]
6382

83+
6484
def monthly_active_users():
6585
return requests.get("https://scratch.mit.edu/statistics/data/monthly/").json()["active_user_data"]
6686

87+
6788
def monthly_activity_trends():
6889
return requests.get("https://scratch.mit.edu/statistics/data/monthly/").json()["activity_data"]
6990

91+
7092
# --- CSRF Token Generation API ---
7193

7294
def get_csrf_token():
@@ -80,32 +102,41 @@ def get_csrf_token():
80102
"https://scratch.mit.edu/csrf_token/"
81103
).headers["set-cookie"].split(";")[3][len(" Path=/, scratchcsrftoken="):]
82104

105+
83106
# --- Various other api.scratch.mit.edu API endpoints ---
84107

85108
def get_health():
86109
return requests.get("https://api.scratch.mit.edu/health").json()
87110

111+
88112
def get_total_project_count() -> int:
89113
return requests.get("https://api.scratch.mit.edu/projects/count/all").json()["count"]
90114

115+
91116
def check_username(username):
92117
return requests.get(f"https://api.scratch.mit.edu/accounts/checkusername/{username}").json()["msg"]
93118

119+
94120
def check_password(password):
95-
return requests.post("https://api.scratch.mit.edu/accounts/checkpassword/", json={"password":password}).json()["msg"]
121+
return requests.post("https://api.scratch.mit.edu/accounts/checkpassword/", json={"password": password}).json()[
122+
"msg"]
123+
96124

97125
# --- April fools endpoints ---
98126

99127
def aprilfools_get_counter() -> int:
100128
return requests.get("https://api.scratch.mit.edu/surprise").json()["surprise"]
101129

130+
102131
def aprilfools_increment_counter() -> int:
103132
return requests.post("https://api.scratch.mit.edu/surprise").json()["surprise"]
104133

134+
105135
# --- Resources ---
106136
def get_resource_urls():
107137
return requests.get("https://resources.scratch.mit.edu/localized-urls.json").json()
108138

139+
109140
# --- Misc ---
110141
# I'm not sure what to label this as
111142
def scratch_team_members() -> dict:
@@ -115,3 +146,20 @@ def scratch_team_members() -> dict:
115146
text = text.split("\"}]')")[0] + "\"}]"
116147

117148
return json.loads(text)
149+
150+
151+
def translate(language: str, text: str = "hello"):
152+
if language not in SUPPORTED_CODES:
153+
if language.lower() in SUPPORTED_CODES:
154+
language = language.lower()
155+
elif language.title() in SUPPORTED_NAMES:
156+
language = SUPPORTED_CODES[SUPPORTED_NAMES.index(language.title())]
157+
else:
158+
warnings.warn(f"'{language}' is probably not a supported language")
159+
response_json = requests.get(
160+
f"https://translate-service.scratch.mit.edu/translate?language={language}&text={text}").json()
161+
162+
if "result" in response_json:
163+
return response_json["result"]
164+
else:
165+
raise BadRequest(f"Language '{language}' does not seem to be valid.\nResponse: {response_json}")

scratchattach/utils/supportedlangs.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
List of supported languages of scratch's translate extension.
3+
Adapted from https://translate-service.scratch.mit.edu/supported?language=en
4+
"""
5+
6+
SUPPORTED_LANGS = {'sq': 'Albanian', 'am': 'Amharic', 'ar': 'Arabic', 'hy': 'Armenian', 'az': 'Azerbaijani',
7+
'eu': 'Basque', 'be': 'Belarusian', 'bg': 'Bulgarian', 'ca': 'Catalan',
8+
'zh-tw': 'Chinese (Traditional)', 'hr': 'Croatian', 'cs': 'Czech', 'da': 'Danish', 'nl': 'Dutch',
9+
'en': 'English', 'eo': 'Esperanto', 'et': 'Estonian', 'fi': 'Finnish', 'fr': 'French',
10+
'gl': 'Galician', 'de': 'German', 'el': 'Greek', 'ht': 'Haitian Creole', 'hi': 'Hindi',
11+
'hu': 'Hungarian', 'is': 'Icelandic', 'id': 'Indonesian', 'ga': 'Irish', 'it': 'Italian',
12+
'ja': 'Japanese', 'kn': 'Kannada', 'ko': 'Korean', 'ku': 'Kurdish (Kurmanji)', 'la': 'Latin',
13+
'lv': 'Latvian', 'lt': 'Lithuanian', 'mk': 'Macedonian', 'ms': 'Malay', 'ml': 'Malayalam',
14+
'mt': 'Maltese', 'mi': 'Maori', 'mr': 'Marathi', 'mn': 'Mongolian', 'my': 'Myanmar (Burmese)',
15+
'fa': 'Persian', 'pl': 'Polish', 'pt': 'Portuguese', 'ro': 'Romanian', 'ru': 'Russian',
16+
'gd': 'Scots Gaelic', 'sr': 'Serbian', 'sk': 'Slovak', 'sl': 'Slovenian', 'es': 'Spanish',
17+
'sv': 'Swedish', 'te': 'Telugu', 'th': 'Thai', 'tr': 'Turkish', 'uk': 'Ukrainian', 'uz': 'Uzbek',
18+
'vi': 'Vietnamese', 'cy': 'Welsh', 'zu': 'Zulu', 'he': 'Hebrew', 'zh-cn': 'Chinese (Simplified)'}
19+
SUPPORTED_CODES = tuple(SUPPORTED_LANGS.keys())
20+
SUPPORTED_NAMES = tuple(SUPPORTED_LANGS.values())
21+
22+
# Code for generating the dict again:
23+
# import requests
24+
#
25+
# SUPPORTED_LANGS = {}
26+
# raw = requests.get("https://translate-service.scratch.mit.edu/supported").json()
27+
# for lang in raw:
28+
# SUPPORTED_LANGS[lang["code"]] = lang["name"]
29+
# print(SUPPORTED_LANGS)

0 commit comments

Comments
 (0)