add
Browse filesFiles changed (5)
- __pycache__/github.cpython-39.pycAdded
- __pycache__/graphql_calls.cpython-39.pycAdded
- app.py+17-47
- github.pyAdded+89
- graphql_calls.py+36-30
12345674 unmodified lines12131415161718191 unmodified line21222324252616 unmodified lines434445464748495 unmodified lines5556575859606110 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241255 unmodified lines131132133134135136137138139140141142143from dataclasses import dataclassimport gradio as grfrom graphql_calls import get_tag_commit_date, get_commits@dataclass4 unmodified linesdef get_release_notes(token: str,repo: str,tag: str,branch: str,contributor_treshhold: int,1 unmodified lineignore_direct: bool,):try:date = get_tag_commit_date(token, repo, tag)commits = get_commits(token, repo, branch, date)except ValueError as e:16 unmodified linescontributors[commit.user.name].descriptions += [commit.message]if "(#" in commit.message:if ignore_dependabot and commit.user.name == 'dependabot[bot]':continuesplit = commit.message.split("(#")5 unmodified linesresult += f"* {commit.message} by @{commit.user.name} (direct commit on {branch})\n"significant_contributors = {k: v for k, v in contributors.items() if (v.additions + v.deletions) > contributor_treshhold and k != '<NOT FOUND>'}if len(significant_contributors):10 unmodified linesreturn resultarticle = """## How to use the interface?⚠️ Most errors are due to:- A wrong `tag` -> the tag must exist on the repository!- A wrong `branch` -> The branch must exist on the repository!- A wrong `token` -> Obtaining a token is detailed below.### tokenThis is a personal access token generated by GitHub. You can obtain one with the following guide:https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token.### RepositoryThe repository for which to create the release notes. Should be in the format `organization/repository`.### TagThe tag from which all commits were made. The app will fetch the date at which this tag was created, and willreturn all commits of the branch defined below that have a timestamp following that date.### BranchThe branch on which all commits lie. Usually `master` or `main`.### ThresholdThis threshold allows highlighting specific community contributors according to the size of their contributions.It currently adds all their additions/deletions across all PRs included in this release. It is then comparedto the defined threshold: if above, that user will get a special note mentioning what they have worked on!"""demo = gr.Interface(title='Automatic release notes 🤗',article=article,description="**See instructions below the form.**",fn=get_release_notes,inputs=[gr.components.Textbox(lines=1, placeholder="Your GitHub token"),gr.components.Textbox(lines=1, placeholder="Repository", value="huggingface/transformers"),gr.components.Textbox(lines=1, placeholder="The tag from which to get commit"),gr.components.Textbox(lines=1,placeholder="The linear branch on which the new version tag will be added",value="main",),gr.components.Slider(minimum=0,5 unmodified linesgr.components.Checkbox(label="Ignore direct commits"),],outputs="text",examples=[['ghp_XXX', 'huggingface/datasets', '2.1.0', 'master', 60, True, True],['ghp_XXX', 'huggingface/accelerate', 'v0.7.1', 'main', 500, True, True],['ghp_XXX', 'huggingface/transformers', 'v4.18.0', 'main', 500, True, True],['ghp_XXX', 'huggingface/diffusers', 'v0.17.0', 'main', 500, True, True],['ghp_XXX', 'gradio-app/gradio', 'v2.9.0', 'main', 500, True, True],],)123456784 unmodified lines1314151617181 unmodified line202122232425262716 unmodified lines444546474849505 unmodified lines56575859606162636410 unmodified lines757677787980818283848586878889909192939495969798991001011025 unmodified lines108109110111112113from dataclasses import dataclassimport osimport gradio as grfrom graphql_calls import get_tag_commit_date, get_commitsfrom github import fetch_github_info@dataclass4 unmodified linesdef get_release_notes(tag: str,branch: str,contributor_treshhold: int,1 unmodified lineignore_direct: bool,):try:token = os.getenv("GITHUB_TOKEN")repo = "huggingface/diffusers"date = get_tag_commit_date(token, repo, tag)commits = get_commits(token, repo, branch, date)except ValueError as e:16 unmodified linescontributors[commit.user.name].descriptions += [commit.message]if "(#" in commit.message:if ignore_dependabot and commit.user.name == "dependabot[bot]":continuesplit = commit.message.split("(#")5 unmodified linesresult += f"* {commit.message} by @{commit.user.name} (direct commit on {branch})\n"significant_contributors = {k: vfor k, v in contributors.items()if (v.additions + v.deletions) > contributor_treshhold and k != "<NOT FOUND>"}if len(significant_contributors):10 unmodified linesreturn resultarticle = """Mostly copied from [lysandre/github-release](https://huggingface.co/spaces/lysandre/github-release) but suited forDiffusers."""github_info = fetch_github_info("https://github.com/huggingface/diffusers")demo = gr.Interface(title="Automatic release notes for 🤗 Diffusers",article=article,description="**See instructions below the form.**",fn=get_release_notes,inputs=[gr.components.Textbox(lines=1,value=github_info["second_last_tag"] if github_info else None,placeholder="The tag from which to get commit",),gr.components.Textbox(lines=1,placeholder="The linear branch on which the new version tag will be added",value=github_info["latest_release_branch"] if github_info else None,),gr.components.Slider(minimum=0,5 unmodified linesgr.components.Checkbox(label="Ignore direct commits"),],outputs="text",)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import requestsfrom functools import lru_cachefrom packaging.version import parseimport os
TOKEN = os.getenv("GITHUB_TOKEN", None)HEADERS = {"Authorization": f"token {TOKEN}"} if TOKEN else {}
@lru_cache()def fetch_all_branches(user, repo): branches = [] # List to store all branches page = 1 # Start from first page while True: # Make a request to the GitHub API for the branches response = requests.get( f"https://api.github.com/repos/{user}/{repo}/branches", params={"page": page}, headers=HEADERS )
# Check if the request was successful if response.status_code == 200: # Add the branches from the current page to the list branches.extend([branch["name"] for branch in response.json()])
# Check if there is a 'next' link for pagination if "next" in response.links: page += 1 # Move to the next page else: break # Exit loop if there is no next page else: print("Failed to retrieve branches:", response.status_code) break
return branches
def fetch_github_info(repo_url): # Extract owner and repo name from the URL repo_parts = repo_url.rstrip("/").split("/") owner, repo = repo_parts[-2], repo_parts[-1] print(f"{owner=}, {repo=}")
# GitHub API base URL api_url = f"https://api.github.com/repos/{owner}/{repo}"
try: # Fetch tags tags_response = requests.get(f"{api_url}/tags", headers=HEADERS) tags_response.raise_for_status() tags = tags_response.json()
if len(tags) < 2: raise ValueError("Not enough tags to fetch the second last tag.")
second_last_tag = tags[1]["name"]
# Fetch branches branches = fetch_all_branches(user=owner, repo=repo) if not branches: raise ValueError("No branches found.")
filtered_branches = [] for branch in branches: if branch.startswith("v") and ("-release" in branch or "-patch" in branch): filtered_branches.append(branch) if not filtered_branches: raise ValueError("No release branches found.")
sorted_branches = sorted(filtered_branches, key=lambda x: parse(x.split("-")[0][1:]), reverse=True) latest_release_branch = sorted_branches[0]
return {"second_last_tag": second_last_tag, "latest_release_branch": latest_release_branch}
except requests.exceptions.RequestException as e: print(f"Error fetching data from GitHub: {e}") return None except ValueError as e: print(e) return None
# Example usageif __name__ == "__main__": repo_url = "https://github.com/huggingface/diffusers" info = fetch_github_info(repo_url)
if info: print("Second Last Tag:", info["second_last_tag"]) print("Latest Release Branch:", info["latest_release_branch"])17 unmodified lines1819202122232425262728293016 unmodified lines47484950515253545556575859606162636465666768697029 unmodified lines1001011021031041051061071081091101111121132 unmodified lines11611711811912012112212312412512612712812913013113213313413513613717 unmodified linesdef call_with_query(query, token):url = 'https://api.github.com/graphql'r = requests.post(url, json={'query': query}, headers={'Authorization': f'Bearer {token}'})return r.json()def get_tag_commit_date(token, repository, tag):owner, name = repository.split('/')query = f"""query GetTagCommit {{repository(owner: "{owner}", name: "{name}"){{16 unmodified linesresponse = call_with_query(query, token)try:repository = response['data']['repository']['object']if repository is None:if 'errors' in response:raise ValueError(response['errors'][0]['message'])raise ValueError('Invalid tag. Does this tag exist?')committed_date = repository['committedDate']except (KeyError, TypeError):raise ValueError('Invalid token. Does your token have the valid permissions?')return committed_datedef get_commits(token, repository, branch, since):owner, name = repository.split('/')def get_page_result(next_page=''):query = f"""query GetCommits {{repository(owner: "{owner}", name: "{name}"){{29 unmodified lines"""result = call_with_query(query, token)if 'data' not in result:raise ValueError(result['errors'][0]['message'])if result['data']['repository']['object'] is None:raise ValueError("Either the tag or the branch were incorrect.")nodes = result['data']['repository']['object']['history']['nodes']cursor = result['data']['repository']['object']['history']['pageInfo']['endCursor']return nodes, cursornodes, cursor = get_page_result()2 unmodified lines_nodes, cursor = get_page_result(f' after:"{cursor}"')nodes.extend(_nodes)commits = []for node in nodes:if node['author']['user'] is None:commits.append(Commit(message=node['message'].split('\n')[0],user=User(name='<NOT FOUND>', organizations=[]),additions=node.get('additions'),deletions=node.get('deletions')))else:commits.append(Commit(message=node['message'].split('\n')[0],user=User(name=node['author']['user']['login'], organizations=[n['name'] for n in node['author']['user']['organizations']['nodes']]),additions=node.get('additions'),deletions=node.get('deletions')))return commits17 unmodified lines1819202122232425262728293016 unmodified lines47484950515253545556575859606162636465666768697029 unmodified lines1001011021031041051061071081091101111121132 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214317 unmodified linesdef call_with_query(query, token):url = "https://api.github.com/graphql"r = requests.post(url, json={"query": query}, headers={"Authorization": f"Bearer {token}"})return r.json()def get_tag_commit_date(token, repository, tag):owner, name = repository.split("/")query = f"""query GetTagCommit {{repository(owner: "{owner}", name: "{name}"){{16 unmodified linesresponse = call_with_query(query, token)try:repository = response["data"]["repository"]["object"]if repository is None:if "errors" in response:raise ValueError(response["errors"][0]["message"])raise ValueError("Invalid tag. Does this tag exist?")committed_date = repository["committedDate"]except (KeyError, TypeError):raise ValueError("Invalid token. Does your token have the valid permissions?")return committed_datedef get_commits(token, repository, branch, since):owner, name = repository.split("/")def get_page_result(next_page=""):query = f"""query GetCommits {{repository(owner: "{owner}", name: "{name}"){{29 unmodified lines"""result = call_with_query(query, token)if "data" not in result:raise ValueError(result["errors"][0]["message"])if result["data"]["repository"]["object"] is None:raise ValueError("Either the tag or the branch were incorrect.")nodes = result["data"]["repository"]["object"]["history"]["nodes"]cursor = result["data"]["repository"]["object"]["history"]["pageInfo"]["endCursor"]return nodes, cursornodes, cursor = get_page_result()2 unmodified lines_nodes, cursor = get_page_result(f' after:"{cursor}"')nodes.extend(_nodes)commits = []for node in nodes:if node["author"]["user"] is None:commits.append(Commit(message=node["message"].split("\n")[0],user=User(name="<NOT FOUND>", organizations=[]),additions=node.get("additions"),deletions=node.get("deletions"),))else:commits.append(Commit(message=node["message"].split("\n")[0],user=User(name=node["author"]["user"]["login"],organizations=[n["name"] for n in node["author"]["user"]["organizations"]["nodes"]],),additions=node.get("additions"),deletions=node.get("deletions"),))return commits
__pycache__/github.cpython-39.pycAdded
__pycache__/graphql_calls.cpython-39.pycAdded
app.py+17-47
github.pyAdded+89
graphql_calls.py+36-30