File size: 15,339 Bytes
f514f40
 
 
 
 
 
e34a465
 
f514f40
 
 
 
 
e34a465
 
 
 
 
f514f40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba413c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e34a465
 
 
 
 
 
fba413c
e34a465
fba413c
e34a465
21be054
 
fba413c
21be054
 
e34a465
 
21be054
e34a465
 
 
f514f40
e34a465
 
 
 
 
 
f514f40
 
 
 
 
 
 
 
 
 
 
 
e34a465
 
 
 
 
 
f514f40
 
e34a465
f514f40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e34a465
f514f40
 
 
 
 
 
 
 
 
e34a465
f514f40
 
 
e34a465
 
 
 
 
 
 
 
 
 
 
 
 
 
b0707cb
e34a465
 
 
 
fba413c
e34a465
 
 
 
 
 
 
b0707cb
e34a465
 
fba413c
e34a465
fba413c
e34a465
 
 
 
 
 
 
f514f40
 
 
 
 
 
 
e34a465
 
 
f514f40
 
e34a465
 
 
 
 
 
f514f40
 
e34a465
f514f40
 
 
 
 
 
 
 
 
 
 
e34a465
 
 
 
 
 
f514f40
 
 
 
e34a465
f514f40
 
 
 
e34a465
f514f40
 
 
fb6f33c
e34a465
 
 
 
 
 
 
f514f40
 
 
e34a465
f514f40
 
 
 
 
e34a465
f514f40
 
 
 
e34a465
 
 
 
 
 
f514f40
 
e34a465
f514f40
 
 
 
 
 
 
 
ac219c3
e34a465
 
f514f40
 
 
 
 
e34a465
 
 
 
 
 
f514f40
e34a465
 
2955c59
e34a465
2955c59
f514f40
e8f04b1
e34a465
 
 
 
 
 
f514f40
e34a465
e8f04b1
7b66718
e8f04b1
f514f40
 
 
 
 
 
 
 
 
 
 
 
 
 
134c3f4
b0707cb
e8f04b1
 
 
f514f40
 
 
 
134c3f4
b0707cb
e8f04b1
 
 
f514f40
 
 
 
134c3f4
b0707cb
 
e8f04b1
 
 
f514f40
e34a465
f514f40
 
134c3f4
b0707cb
e8f04b1
 
 
f514f40
e34a465
 
 
 
 
 
b0707cb
e34a465
a4a0af8
b0707cb
066b297
b0707cb
e34a465
b0707cb
e34a465
b0707cb
e34a465
a4a0af8
f514f40
 
 
 
 
e34a465
 
 
 
 
 
f514f40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from typing import Dict, Any, List

import ast
import tarfile
import torch
import requests
import numpy as np
from ast import AsyncFunctionDef, ClassDef, FunctionDef, Module
from transformers import Pipeline
from tqdm.auto import tqdm


def 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)
    for node in ast.walk(root):
        if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
            continue
        docs = ast.get_docstring(node)
        node_without_docs = node
        if docs is not None:
            docs_set.add(docs)
            # Remove docstrings from the node
            node_without_docs.body = node_without_docs.body[1:]
        if isinstance(node, (AsyncFunctionDef, FunctionDef)):
            code_set.add(ast.unparse(node_without_docs))

    return code_set, docs_set


def extract_readmes(file_content):
    """
    The method for extracting readmes.
    :param lines: readmes.
    :return: readme sentences.
    """
    readmes_set = set()
    lines = file_content.split('\n')
    for line in lines:
        line = line.replace("\n", "").strip()
        readmes_set.add(line)

    return readmes_set


def extract_requirements(file_content):
    """
    The method for extracting requirements.
    :param lines: requirements.
    :return: requirement libraries.
    """
    requirements_set = set()
    lines = file_content.split('\n')
    for line in lines:
        line = line.replace("\n", "").strip()
        try:
            if " == " in line:
                splitLine = line.split(" == ")
            else:
                splitLine = line.split("==")
            requirements_set.add(splitLine[0])
        except:
            pass

    return requirements_set


def 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:
        response = requests.get(api_url, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        tqdm.write(f"[-] Failed to retrieve metadata from {repo_name}: {e}")
        return {}


def 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,
            "codes": set(),
            "docs": set(),
            "requirements": set(),
            "readmes": set(),
            "topics": [],
            "license": "",
            "stars": metadata.get("stargazers_count"),
        }
        if metadata.get("topics"):
            repo_info["topics"] = metadata["topics"]
        if 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:
            response = requests.get(download_url, headers=headers, stream=True)
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            tqdm.write(f"[-] Failed to download {repo_name}: {e}")
            continue

        # Extract repository files and parse them
        tqdm.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_docs
                        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}")
                # 3. Extracting readme.
                elif (member.name.endswith("README.md") or member.name.endswith("README.rst")) and member.isfile():
                    try:
                        file_content = tar.extractfile(member).read().decode("utf-8")
                        # extract readme
                        readmes_set = extract_readmes(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}")
                # 4. Extracting requirements.
                elif member.name.endswith("requirements.txt") and member.isfile():
                    try:
                        file_content = tar.extractfile(member).read().decode("utf-8")
                        # extract readme
                        requirements_set = extract_requirements(file_content)
                        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)

    return extracted_infos


class 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 token
        self.github_token = github_token
        if self.github_token:
            print("[+] GitHub token set!")
        else:
            print(
                "[*] Please set GitHub token to avoid unexpected errors. \n"
                "For more info, see: "
                "https://docs.github.com/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token"
            )

    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_parameters

    def 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_token
        if 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_infos

    def 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.tokenizer
        tokens = (
                [tokenizer.cls_token, "<encoder-only>", tokenizer.sep_token]
                + tokenizer.tokenize(text)[: max_length - 4]
                + [tokenizer.sep_token]
        )
        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_embeddings

    def 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, st_progress=None) -> 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_texts = sum(
            len(x["codes"]) + len(x["docs"]) + len(x["requirements"]) + len(x["readmes"]) for x in extracted_infos)
        with tqdm(total=num_texts) as progress_bar:
            # For each repository
            for repo_info in extracted_infos:
                repo_name = repo_info["name"]
                info = {
                    "name": repo_name,
                    "topics": repo_info["topics"],
                    "license": repo_info["license"],
                    "stars": repo_info["stars"],
                }
                progress_bar.set_description(f"Processing {repo_name}")

                # Code embeddings
                tqdm.write(f"[*] Generating code embeddings for {repo_name}")
                code_embeddings = self.generate_embeddings(repo_info["codes"], max_length)
                info["code_embeddings"] = code_embeddings.cpu().numpy()
                info["mean_code_embedding"] = torch.mean(code_embeddings, dim=0, keepdim=True).cpu().numpy()
                progress_bar.update(len(repo_info["codes"]))
                if st_progress:
                    st_progress.progress(progress_bar.n / progress_bar.total)

                # Doc embeddings
                tqdm.write(f"[*] Generating doc embeddings for {repo_name}")
                doc_embeddings = self.generate_embeddings(repo_info["docs"], max_length)
                info["doc_embeddings"] = doc_embeddings.cpu().numpy()
                info["mean_doc_embedding"] = torch.mean(doc_embeddings, dim=0, keepdim=True).cpu().numpy()
                progress_bar.update(len(repo_info["docs"]))
                if st_progress:
                    st_progress.progress(progress_bar.n / progress_bar.total)

                # Requirement embeddings
                tqdm.write(f"[*] Generating requirement embeddings for {repo_name}")
                requirement_embeddings = self.generate_embeddings(repo_info["requirements"], max_length)
                info["requirement_embeddings"] = requirement_embeddings.cpu().numpy()
                info["mean_requirement_embedding"] = torch.mean(requirement_embeddings, dim=0,
                                                                keepdim=True).cpu().numpy()
                progress_bar.update(len(repo_info["requirements"]))
                if st_progress:
                    st_progress.progress(progress_bar.n / progress_bar.total)

                # Readme embeddings
                tqdm.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, keepdim=True).cpu().numpy()
                progress_bar.update(len(repo_info["readmes"]))
                if st_progress:
                    st_progress.progress(progress_bar.n / progress_bar.total)

                # Repo-level mean embedding
                info["mean_repo_embedding"] = np.concatenate([
                    info["mean_code_embedding"],
                    info["mean_doc_embedding"],
                    info["mean_requirement_embedding"],
                    info["mean_readme_embedding"]
                ], axis=0).reshape(1, -1)

                info["code_embeddings_shape"] = info["code_embeddings"].shape
                info["mean_code_embedding_shape"] = info["mean_code_embedding"].shape
                info["doc_embeddings_shape"] = info["doc_embeddings"].shape
                info["mean_doc_embedding_shape"] = info["mean_doc_embedding"].shape
                info["requirement_embeddings_shape"] = info["requirement_embeddings"].shape
                info["mean_requirement_embedding_shape"] = info["mean_requirement_embedding"].shape
                info["readme_embeddings_shape"] = info["readme_embeddings"].shape
                info["mean_readme_embedding_shape"] = info["mean_readme_embedding"].shape
                info["mean_repo_embedding_shape"] = info["mean_repo_embedding"].shape

                model_outputs.append(info)

        return model_outputs

    def 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