Feature Extraction
Transformers
PyTorch
roberta
code-understanding
unixcoder
text-embeddings-inference
Run this model with HF Jobs
Run Henry65/RepoSim4Py on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Henry65/RepoSim4Py. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Henry65/RepoSim4Py on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Henry65/RepoSim4Py with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Henry65/RepoSim4Py with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Henry65/RepoSim4Py")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("Henry65/RepoSim4Py") model = AutoModel.from_pretrained("Henry65/RepoSim4Py", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update RepoPipeline.py
Browse files1 unmodified line2345678910111213141512 unmodified lines282930313233346 unmodified lines41424344454647484910 unmodified lines606162636465663 unmodified lines7071727374757677787980818283848586878889909192931 unmodified line95969798991001011021031041055 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451462 unmodified lines14915015115215315415515615715815916016116216316416516616716825 unmodified lines1941951961971981992002012022032042052062071 unmodified line2092102112122132141 unmodified lineimport astimport tarfilefrom ast import AsyncFunctionDef, ClassDef, FunctionDef, Moduleimport torchimport requestsfrom transformers import Pipelinefrom tqdm.auto import tqdmdef extract_code_and_docs(text: str):code_set = set()docs_set = set()root = ast.parse(text)12 unmodified linesreturn code_set, docs_setdef get_metadata(repo_name, headers=None):api_url = f"https://api.github.com/repos/{repo_name}"tqdm.write(f"[+] Getting metadata for {repo_name}")try:6 unmodified linesdef extract_information(repos, headers=None):extracted_infos = []for repo_name in tqdm(repos, disable=len(repos) <= 1):# Get metadatametadata = get_metadata(repo_name, headers=headers)repo_info = {"name": repo_name,10 unmodified linesif metadata.get("license"):repo_info["license"] = metadata["license"]["spdx_id"]# Download repo tarball bytesdownload_url = f"https://api.github.com/repos/{repo_name}/tarball"tqdm.write(f"[+] Downloading {repo_name}")try:3 unmodified linestqdm.write(f"[-] Failed to download {repo_name}: {e}")continue# Extract python files and parse themtqdm.write(f"[+] Extracting {repo_name} info")with tarfile.open(fileobj=response.raw, mode="r|gz") as tar:for member in tar:if (member.name.endswith(".py") and member.isfile()) is False:continuetry:file_content = tar.extractfile(member).read().decode("utf-8")code_set, docs_set = extract_code_and_docs(file_content)repo_info["codes"].update(code_set)repo_info["docs"].update(docs_set)except UnicodeDecodeError as e:tqdm.write(f"[-] UnicodeDecodeError in {member.name}, skipping: \n{e}")except SyntaxError as e:tqdm.write(f"[-] SyntaxError in {member.name}, skipping: \n{e}")extracted_infos.append(repo_info)1 unmodified lineclass RepoPipeline(Pipeline):def __init__(self, github_token=None, *args, **kwargs):super().__init__(*args, **kwargs)# Github tokenself.github_token = github_tokenif self.github_token:print("[+] GitHub token set!")5 unmodified lines)def _sanitize_parameters(self, **pipeline_parameters):preprocess_parameters = {}if "github_token" in pipeline_parameters:preprocess_parameters["github_token"] = pipeline_parameters["github_token"]forward_parameters = {}if "max_length" in pipeline_parameters:forward_parameters["max_length"] = pipeline_parameters["max_length"]postprocess_parameters = {}return preprocess_parameters, forward_parameters, postprocess_parametersdef preprocess(self, input_: Any, github_token=None) -> List:# Making input to list formatif isinstance(input_, str):input_ = [input_]# Building tokenheaders = {"Accept": "application/vnd.github+json"}token = github_token or self.github_tokenif token:headers["Authorization"] = f"Bearer {token}"# Getting repositories' information: input_ means series of repositoriesextracted_infos = extract_information(input_, headers=headers)return extracted_infosdef encode(self, text, max_length):assert max_length < 1024tokenizer = self.tokenizertokens = ([tokenizer.cls_token, "<encoder-only>", tokenizer.sep_token]2 unmodified lines)tokens_id = tokenizer.convert_tokens_to_ids(tokens)source_ids = torch.tensor([tokens_id]).to(self.device)token_embeddings = self.model(source_ids)[0]sentence_embeddings = token_embeddings.mean(dim=1)return sentence_embeddingsdef generate_embeddings(self, text_sets, max_length):assert max_length < 1024return torch.zeros((1, 768), device=self.device) \if text_sets is None or len(text_sets) == 0 \else torch.cat([self.encode(text, max_length) for text in text_sets], dim=0)def _forward(self, extracted_infos: List, max_length=512) -> List:model_outputs = []num_repos = len(extracted_infos)with tqdm(total=num_repos) as progress_bar:# For each repository25 unmodified linesinfo["requirement_embeddings"] = requirement_embeddings.cpu().numpy()info["mean_requirement_embedding"] = torch.mean(requirement_embeddings, dim=0).cpu().numpy()# Requirement embeddingstqdm.write(f"[*] Generating readme embeddings for {repo_name}")readme_embeddings = self.generate_embeddings(repo_info["readmes"], max_length)info["readme_embeddings"] = readme_embeddings.cpu().numpy()info["mean_readme_embedding"] = torch.mean(readme_embeddings, dim=0).cpu().numpy()info["code_embeddings_shape"] = info["code_embeddings"].shapeinfo["doc_embeddings_shape"] = info["doc_embeddings"].shapeprogress_bar.update(1)model_outputs.append(info)1 unmodified linereturn model_outputsdef postprocess(self, model_outputs: List, **postprocess_parameters: Dict) -> List:return model_outputs1 unmodified line2345678910111213141516171819202112 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666 unmodified lines73747576777879808182838485868710 unmodified lines98991001011021031043 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581 unmodified line1601611621631641651661671681691701711721731741751761771781795 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402 unmodified lines24324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727825 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283291 unmodified line3313323333343353363373383393401 unmodified lineimport astimport tarfileimport torchimport requestsimport numpy as npfrom ast import AsyncFunctionDef, ClassDef, FunctionDef, Modulefrom transformers import Pipelinefrom tqdm.auto import tqdmdef extract_code_and_docs(text: str):"""The method for extracting codes and docs in text.:param text: python file.:return: codes and docs set."""code_set = set()docs_set = set()root = ast.parse(text)12 unmodified linesreturn code_set, docs_setdef extract_requirements(lines):"""The method for extracting requirements.:param lines: requirements.:return: requirement libraries."""requirements_set = set()for line in lines:try:if line != "\n":if " == " in line:splitLine = line.split(" == ")else:splitLine = line.split("==")requirements_set.add(splitLine[0])except:passreturn requirements_setdef get_metadata(repo_name, headers=None):"""The method for getting metadata of repository from github_api.:param repo_name: repository name.:param headers: request headers.:return: response json."""api_url = f"https://api.github.com/repos/{repo_name}"tqdm.write(f"[+] Getting metadata for {repo_name}")try:6 unmodified linesdef extract_information(repos, headers=None):"""The method for extracting repositories information.:param repos: repositories.:param headers: request header.:return: a list for representing the information of each repository."""extracted_infos = []for repo_name in tqdm(repos, disable=len(repos) <= 1):# 1. Extracting metadata.metadata = get_metadata(repo_name, headers=headers)repo_info = {"name": repo_name,10 unmodified linesif metadata.get("license"):repo_info["license"] = metadata["license"]["spdx_id"]# Download repo tarball bytes ---- Download repository.download_url = f"https://api.github.com/repos/{repo_name}/tarball"tqdm.write(f"[+] Downloading {repo_name}")try:3 unmodified linestqdm.write(f"[-] Failed to download {repo_name}: {e}")continue# Extract repository files and parse themtqdm.write(f"[+] Extracting {repo_name} info")with tarfile.open(fileobj=response.raw, mode="r|gz") as tar:for member in tar:# 2. Extracting codes and docs.if member.name.endswith(".py") and member.isfile():try:file_content = tar.extractfile(member).read().decode("utf-8")# extract_code_and_docscode_set, docs_set = extract_code_and_docs(file_content)repo_info["codes"].update(code_set)repo_info["docs"].update(docs_set)except UnicodeDecodeError as e:tqdm.write(f"[-] UnicodeDecodeError in {member.name}, skipping: \n{e}")except SyntaxError as e:tqdm.write(f"[-] SyntaxError in {member.name}, skipping: \n{e}")elif (member.name.endswith("README.md") or member.name.endswith("README.rst")) and member.isfile():# 3. Extracting readme.try:file_content = tar.extractfile(member).read().decode("utf-8")# extract readmereadmes_set = set()readmes_set.add(file_content)repo_info["readmes"].update(readmes_set)except UnicodeDecodeError as e:tqdm.write(f"[-] UnicodeDecodeError in {member.name}, skipping: \n{e}")except SyntaxError as e:tqdm.write(f"[-] SyntaxError in {member.name}, skipping: \n{e}")elif member.name.endswith("requirements.txt") and member.isfile():# 4. Extracting requirements.try:lines = tar.extractfile(member).readlines().decode("utf-8")# extract readmerequirements_set = extract_requirements(lines)repo_info["requirements"].update(requirements_set)except UnicodeDecodeError as e:tqdm.write(f"[-] UnicodeDecodeError in {member.name}, skipping: \n{e}")except SyntaxError as e:tqdm.write(f"[-] SyntaxError in {member.name}, skipping: \n{e}")extracted_infos.append(repo_info)1 unmodified lineclass RepoPipeline(Pipeline):"""A custom pipeline for generating series of embeddings of a repository."""def __init__(self, github_token=None, *args, **kwargs):"""The initial method for pipeline.:param github_token: github_token:param args: args:param kwargs: kwargs"""super().__init__(*args, **kwargs)# Getting github tokenself.github_token = github_tokenif self.github_token:print("[+] GitHub token set!")5 unmodified lines)def _sanitize_parameters(self, **pipeline_parameters):"""The method for splitting parameters.:param pipeline_parameters: parameters:return: different parameters of different periods."""# The parameters of "preprocess" period.preprocess_parameters = {}if "github_token" in pipeline_parameters:preprocess_parameters["github_token"] = pipeline_parameters["github_token"]# The parameters of "forward" period.forward_parameters = {}if "max_length" in pipeline_parameters:forward_parameters["max_length"] = pipeline_parameters["max_length"]# The parameters of "postprocess" period.postprocess_parameters = {}return preprocess_parameters, forward_parameters, postprocess_parametersdef preprocess(self, input_: Any, github_token=None) -> List:"""The method for "preprocess" period.:param input_: the input.:param github_token: github_token.:return: a list about repository information."""# Making input to list format.if isinstance(input_, str):input_ = [input_]# Building headers.headers = {"Accept": "application/vnd.github+json"}token = github_token or self.github_tokenif token:headers["Authorization"] = f"Bearer {token}"# Getting repositories' information: input_ means series of repositories (can be only one repository).extracted_infos = extract_information(input_, headers=headers)return extracted_infosdef encode(self, text, max_length):"""The method for encoding the text to embedding by using UniXcoder.:param text: text.:param max_length: the max length.:return: the embedding of text."""assert max_length < 1024# Getting the tokenizer.tokenizer = self.tokenizertokens = ([tokenizer.cls_token, "<encoder-only>", tokenizer.sep_token]2 unmodified lines)tokens_id = tokenizer.convert_tokens_to_ids(tokens)source_ids = torch.tensor([tokens_id]).to(self.device)token_embeddings = self.model(source_ids)[0]# Getting the text embedding.sentence_embeddings = token_embeddings.mean(dim=1)return sentence_embeddingsdef generate_embeddings(self, text_sets, max_length):"""The method for generating embeddings of a text set.:param text_sets: text set.:param max_length: max length.:return: the embeddings of text set."""assert max_length < 1024# Concat the embeddings of each sentence/text in vertical dimension.return torch.zeros((1, 768), device=self.device) \if not text_sets \else torch.cat([self.encode(text, max_length) for text in text_sets], dim=0)def _forward(self, extracted_infos: List, max_length=512) -> List:"""The method for "forward" period.:param extracted_infos: the information of repositories.:param max_length: max length.:return: the output of this pipeline."""model_outputs = []# The number of repository.num_repos = len(extracted_infos)with tqdm(total=num_repos) as progress_bar:# For each repository25 unmodified linesinfo["requirement_embeddings"] = requirement_embeddings.cpu().numpy()info["mean_requirement_embedding"] = torch.mean(requirement_embeddings, dim=0).cpu().numpy()# Readme embeddingstqdm.write(f"[*] Generating readme embeddings for {repo_name}")readme_embeddings = self.generate_embeddings(repo_info["readmes"], max_length)info["readme_embeddings"] = readme_embeddings.cpu().numpy()info["mean_readme_embedding"] = torch.mean(readme_embeddings, dim=0).cpu().numpy()# Repo-level mean embeddinginfo["mean_repo_embedding"] = np.concatenate([info["mean_code_embedding"],info["mean_doc_embedding"],info["mean_requirement_embedding"],info["mean_readme_embedding"]], axis=0)# TODO Remove testinfo["code_embeddings_shape"] = info["code_embeddings"].shapeinfo["doc_embeddings_shape"] = info["doc_embeddings"].shapeinfo["requirement_embeddings_shape"] = info["requirement_embeddings"].shapeinfo["readme_embeddings_shape"] = info["readme_embeddings"].shapeinfo["mean_repo_embedding_shape"] = info["mean_repo_embedding"].shapeprogress_bar.update(1)model_outputs.append(info)1 unmodified linereturn model_outputsdef postprocess(self, model_outputs: List, **postprocess_parameters: Dict) -> List:"""The method for "postprocess" period.:param model_outputs: the output of this pipeline.:param postprocess_parameters: the parameters of "postprocess" period.:return: model output."""return model_outputs
RepoPipeline.py+154-28