Skip to content

Commit 94c27a1

Browse files
authored
Improve tx_stats.py (#237)
* Improve TX_TOKEN check * Refactor tx_stats.py
1 parent cbfc851 commit 94c27a1

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
import json
55
import os
6+
import configparser
67
import urllib.request
78
from datetime import datetime, 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-
with urllib.request.urlopen(request) as response:
26-
data = json.loads(response.read().decode("utf-8"))
27-
url = data['links'].get('next')
28-
for resourse in data['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+
if language is None:
14+
raise ValueError("The PYDOC_LANGUAGE environment variable must be set.")
15+
if project is None:
16+
raise ValueError("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+
def get_transifex_token():
21+
key = os.environ.get("TX_TOKEN")
22+
if key is None:
23+
config = configparser.ConfigParser()
24+
config.read(os.path.expanduser("~/.transifexrc"))
25+
try:
26+
key = config["https://www.transifex.com"]["token"]
27+
except KeyError:
28+
raise ValueError("Unable to retrieve Transifex API token.")
29+
return key
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+
def fetch_data(url):
53+
request = urllib.request.Request(url=url, headers=headers)
54+
try:
55+
with urllib.request.urlopen(request) as response:
56+
return json.loads(response.read().decode("utf-8"))
57+
except urllib.error.URLError as e:
58+
raise ConnectionError(f"Error fetching data: {e}")
59+
except json.JSONDecodeError as e:
60+
raise ValueError(f"Error decoding JSON response: {e}")
61+
62+
63+
# Fetch and process translation stats
64+
while url:
65+
data = fetch_data(url)
66+
url = data["links"].get("next")
67+
for resource in data["data"]:
68+
translated_strings += resource["attributes"]["translated_strings"]
69+
total_strings += resource["attributes"]["total_strings"]
70+
71+
# Calculate translation percentage
72+
if total_strings == 0:
73+
raise ValueError("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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy