Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit94c27a1

Browse files
authored
Improve tx_stats.py (#237)
* Improve TX_TOKEN check* Refactor tx_stats.py
1 parentcbfc851 commit94c27a1

File tree

2 files changed

+90
-30
lines changed

2 files changed

+90
-30
lines changed

‎.github/workflows/sync.yml

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,16 @@ jobs:
5858
requirements.txt
5959
cpython/Doc/requirements.txt
6060
61+
-name:Check for Transifex API Token availability
62+
id:secret-check
63+
# perform secret check & put boolean result as an output
64+
shell:bash
65+
run:|
66+
available=false
67+
[ "${{ secrets.TX_TOKEN }}" != '' ] && available=true
68+
echo "available=$available" >> $GITHUB_OUTPUT
69+
echo "available=$available"
70+
6171
# 2- Install dependencies
6272

6373
-name:Install Transifex CLI tool
@@ -95,7 +105,7 @@ jobs:
95105
powrap *.po **/*.po
96106
97107
-name:Update statistics
98-
if:always() &&inputs.secrets.TX_TOKEN !=0
108+
if:always() &&${{ steps.secret-check.outputs.available !='true' }}
99109
run:|
100110
python ./scripts/tx_stats.py > ./${{ env.LANGUAGE_DIR }}/stats.json
101111
git -C ./${{ env.LANGUAGE_DIR }} diff stats.json

‎scripts/tx_stats.py

Lines changed: 79 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,85 @@
33

44
importjson
55
importos
6+
importconfigparser
67
importurllib.request
78
fromdatetimeimportdatetime,timezone
89

9-
key=os.environ.get('TX_TOKEN')
10-
language=os.environ.get('PYDOC_LANGUAGE')
11-
project=os.environ.get('PYDOC_TX_PROJECT')
12-
13-
url="https://rest.api.transifex.com/resource_language_stats?filter[project]=o%3Apython-doc%3Ap%3A{tx_project}&filter[language]=l%3A{langcode}".format(tx_project=project,langcode=language)
14-
15-
headers= {
16-
"accept":"application/vnd.api+json",
17-
"authorization":"Bearer "+key
18-
}
19-
20-
total=0
21-
translated=0
22-
23-
while(url):
24-
request=urllib.request.Request(url=url,headers=headers)
25-
withurllib.request.urlopen(request)asresponse:
26-
data=json.loads(response.read().decode("utf-8"))
27-
url=data['links'].get('next')
28-
forresourseindata['data']:
29-
translated=translated+resourse['attributes']['translated_strings']
30-
total=total+resourse['attributes']['total_strings']
31-
32-
p='{:.2%}'.format(translated/total)
33-
print(json.dumps({
34-
'translation':p,
35-
'total':total,
36-
'updated_at':datetime.now(timezone.utc).isoformat(timespec='seconds')+'Z',
37-
}))
10+
# Get language and project from environment variables
11+
language=os.environ.get("PYDOC_LANGUAGE")
12+
project=os.environ.get("PYDOC_TX_PROJECT")
13+
iflanguageisNone:
14+
raiseValueError("The PYDOC_LANGUAGE environment variable must be set.")
15+
ifprojectisNone:
16+
raiseValueError("The PYDOC_TX_PROJECT environment variable must be set.")
17+
18+
19+
# Try to read API token from TX_TOKEN env and then from ~/.transifexrc
20+
defget_transifex_token():
21+
key=os.environ.get("TX_TOKEN")
22+
ifkeyisNone:
23+
config=configparser.ConfigParser()
24+
config.read(os.path.expanduser("~/.transifexrc"))
25+
try:
26+
key=config["https://www.transifex.com"]["token"]
27+
exceptKeyError:
28+
raiseValueError("Unable to retrieve Transifex API token.")
29+
returnkey
30+
31+
32+
# API URL setup
33+
url_template= (
34+
"https://rest.api.transifex.com/resource_language_stats"
35+
"?filter[project]=o%3Apython-doc%3Ap%3A{project}"
36+
"&filter[language]=l%3A{language}"
37+
)
38+
39+
# Get the authorization key
40+
key=get_transifex_token()
41+
42+
url=url_template.format(project=project,language=language)
43+
44+
headers= {"accept":"application/vnd.api+json","authorization":f"Bearer{key}"}
45+
46+
# Initialize counters
47+
total_strings=0
48+
translated_strings=0
49+
50+
51+
# Function to make an API request and handle potential errors
52+
deffetch_data(url):
53+
request=urllib.request.Request(url=url,headers=headers)
54+
try:
55+
withurllib.request.urlopen(request)asresponse:
56+
returnjson.loads(response.read().decode("utf-8"))
57+
excepturllib.error.URLErrorase:
58+
raiseConnectionError(f"Error fetching data:{e}")
59+
exceptjson.JSONDecodeErrorase:
60+
raiseValueError(f"Error decoding JSON response:{e}")
61+
62+
63+
# Fetch and process translation stats
64+
whileurl:
65+
data=fetch_data(url)
66+
url=data["links"].get("next")
67+
forresourceindata["data"]:
68+
translated_strings+=resource["attributes"]["translated_strings"]
69+
total_strings+=resource["attributes"]["total_strings"]
70+
71+
# Calculate translation percentage
72+
iftotal_strings==0:
73+
raiseValueError("Total strings cannot be zero.")
74+
75+
percentage=f"{(translated_strings/total_strings):.2%}"
76+
77+
# Print the result as JSON
78+
print(
79+
json.dumps(
80+
{
81+
"translation":percentage,
82+
"total":total_strings,
83+
"updated_at":datetime.now(timezone.utc).isoformat(timespec="seconds")
84+
+"Z",
85+
}
86+
)
87+
)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp