sayakpaul HF staff commited on
Commit
bc69905
1 Parent(s): 226e982

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +32 -0
  2. requirements.txt +3 -0
  3. utils.py +133 -0
app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import utils
3
+
4
+ DESCRIPTION = """
5
+ This Space helps you find out the top-n slow tests from a particular GitHub Action run step. It also buckets the tests w.r.t their durations.
6
+ """
7
+
8
+ ARTICLE = """
9
+ To obtain the article name you're looking for, you need to scroll down the run page (for [example](https://github.com/huggingface/diffusers/actions/runs/8430950874/)) and select one from the 'Artifacts' section.
10
+ """
11
+
12
+ with gr.Interface(
13
+ fn=utils.analyze_tests,
14
+ inputs=[
15
+ gr.Textbox(info="GitHub repository ID", placeholder="huggingface/diffusers"),
16
+ gr.Textbox(placeholder="GitHub token", type="password"),
17
+ gr.Textbox(placeholder="GitHub Action run ID"),
18
+ gr.Textbox(info="Artifact name", placeholder="pr_flax_cpu_test_reports"),
19
+ gr.Slider(2, 20, value=1, label="top-n", info="Top-n slow tests."),
20
+ ],
21
+ outputs=gr.Markdown(label="output"),
22
+ examples=[
23
+ ['huggingface/diffusers', 'ghp_XXX', '8430950874', 'pr_torch_cpu_pipelines_test_reports', 5],
24
+ ],
25
+ title="Short analysis of PR tests!",
26
+ description=DESCRIPTION,
27
+ article=ARTICLE,
28
+ allow_flagging="never",
29
+ cache_examples=False,
30
+ ) as demo:
31
+ demo.queue()
32
+ demo.launch(show_error=True)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ zipfile
2
+ tempfile
3
+ requests
utils.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import zipfile
3
+ import tempfile
4
+
5
+ def group_tests_by_duration(file_path: str) -> dict:
6
+ # Define the buckets and their labels
7
+ buckets = [(0, 5), (5, 10), (10, 15), (15, 20), (20, float('inf'))]
8
+ bucket_names = ["0-5s", "5-10s", "10-15s", "15-20s", ">20s"]
9
+ test_groups = {name: [] for name in bucket_names}
10
+
11
+ # Process the file with error handling
12
+ with open(file_path, 'r') as file:
13
+ for line in file:
14
+ try:
15
+ parts = line.split()
16
+ # Extracting duration and test name, ignoring lines that don't match expected format
17
+ if len(parts) >= 3 and 's' in parts[0]:
18
+ duration = float(parts[0].rstrip('s')) # Remove 's' and convert to float
19
+ test_name = ' '.join(parts[2:]) # Join back the test name parts
20
+
21
+ # Assign test to the correct bucket based on duration
22
+ for (start, end), bucket_name in zip(buckets, bucket_names):
23
+ if start <= duration < end:
24
+ test_groups[bucket_name].append((duration, test_name))
25
+ break
26
+ except ValueError:
27
+ # Skip lines that cannot be parsed properly
28
+ continue
29
+
30
+ return test_groups
31
+
32
+
33
+ def extract_top_n_tests(file_path, n=10):
34
+ test_durations = []
35
+
36
+ # Reading and processing the file
37
+ with open(file_path, 'r') as file:
38
+ for line in file:
39
+ parts = line.split()
40
+ if len(parts) >= 3 and parts[1] == 'call':
41
+ duration_s = parts[0].rstrip('s') # Remove the 's' from the duration
42
+ try:
43
+ duration = float(duration_s)
44
+ test_name = ' '.join(parts[2:])
45
+ test_durations.append((duration, test_name))
46
+ except ValueError:
47
+ # Skip lines that cannot be converted to float
48
+ continue
49
+
50
+ # Sort the list in descending order of duration
51
+ test_durations.sort(reverse=True, key=lambda x: x[0])
52
+
53
+ # Extract the top N tests
54
+ top_n_tests = {test[1]: f"{test[0]}s"
55
+ for i, test in enumerate(test_durations[:n])}
56
+
57
+ return top_n_tests
58
+
59
+
60
+ def fetch_test_duration_artifact(repo_id, token, run_id, artifact_name):
61
+ # Construct the API URL
62
+ owner_repo = repo_id.split("/")
63
+ artifacts_url = f'https://api.github.com/repos/{owner_repo[0]}/{owner_repo[1]}/actions/runs/{run_id}/artifacts'
64
+
65
+ # Set up the headers with your authentication token
66
+ headers = {'Authorization': f'token {token}'}
67
+
68
+ # Send the request to get a list of artifacts from the specified run
69
+ response = requests.get(artifacts_url, headers=headers)
70
+ response.raise_for_status() # Raise an exception for HTTP error responses
71
+
72
+ # Search for the artifact with the specified name
73
+ download_url = None
74
+ for artifact in response.json().get('artifacts', []):
75
+ if artifact['name'] == artifact_name:
76
+ download_url = artifact['archive_download_url']
77
+ break
78
+
79
+ if download_url:
80
+ # Download the artifact
81
+ download_response = requests.get(download_url, headers=headers, stream=True)
82
+ download_response.raise_for_status()
83
+
84
+ # Save the downloaded artifact to a file
85
+ zip_file_path = f'{artifact_name}.zip'
86
+ with open(zip_file_path, 'wb') as file:
87
+ for chunk in download_response.iter_content(chunk_size=128):
88
+ file.write(chunk)
89
+
90
+ # Extract the duration text file
91
+ with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
92
+ # Check if the specified file exists in the zip
93
+ zip_files = zip_ref.namelist()
94
+ for file in zip_files:
95
+ if "duration" in file:
96
+ zip_ref.extract(file, ".")
97
+ break
98
+ return file
99
+
100
+ else:
101
+ raise ValueError("Error 🥲")
102
+
103
+ def format_to_markdown_str(test_bucket_map, top_n_slow_tests, repo_id, run_id, artifact_name):
104
+ run_url = f"https://github.com/{repo_id}/actions/runs/{run_id}/"
105
+ markdown_str = f"""
106
+ ## Top {len(top_n_slow_tests)} slow test for {artifact_name}\n
107
+ """
108
+ for test, duration in top_n_slow_tests.items():
109
+ markdown_str += f"* {test.split('/')[-1]}: {duration}\n"
110
+
111
+ markdown_str += """
112
+ ## Bucketed durations of the tests\n
113
+ """
114
+ for bucket, num_tests in test_bucket_map.items():
115
+ if ">" in bucket:
116
+ bucket = f"\{bucket}"
117
+ markdown_str += f"* {bucket}: {num_tests} tests\n"
118
+
119
+ markdown_str += f"\nRun URL: [{run_url}]({run_url})."
120
+
121
+ return markdown_str
122
+
123
+
124
+ def analyze_tests(repo_id, token, run_id, artifact_name, top_n):
125
+ test_duration_file = fetch_test_duration_artifact(repo_id=repo_id, token=token, run_id=run_id, artifact_name=artifact_name)
126
+
127
+ grouped_tests_map = group_tests_by_duration(test_duration_file)
128
+ test_bucket_map = {bucket: len(tests) for bucket, tests in grouped_tests_map.items()}
129
+ print(test_bucket_map)
130
+ top_n_slow_tests = extract_top_n_tests(test_duration_file, n=top_n)
131
+ print(top_n_slow_tests)
132
+
133
+ return format_to_markdown_str(test_bucket_map, top_n_slow_tests, repo_id, run_id, artifact_name)