nn-rag 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ab/__init__.py +0 -0
- ab/rag/__init__.py +0 -0
- ab/rag/api.py +63 -0
- ab/rag/config/__init__.py +0 -0
- ab/rag/config/config.py +9 -0
- ab/rag/main.py +19 -0
- ab/rag/utils/__init__.py +0 -0
- ab/rag/utils/github_utils.py +52 -0
- ab/rag/utils/neural_utils.py +75 -0
- nn_rag-0.1.0.dist-info/METADATA +27 -0
- nn_rag-0.1.0.dist-info/RECORD +14 -0
- nn_rag-0.1.0.dist-info/WHEEL +5 -0
- nn_rag-0.1.0.dist-info/licenses/LICENSE +22 -0
- nn_rag-0.1.0.dist-info/top_level.txt +1 -0
ab/__init__.py
ADDED
|
File without changes
|
ab/rag/__init__.py
ADDED
|
File without changes
|
ab/rag/api.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from pandas import DataFrame
|
|
2
|
+
from utils.github_utils import build_query, search_repositories_with_cache
|
|
3
|
+
from utils.neural_utils import neural_rank_repositories, generate_response_from_results
|
|
4
|
+
|
|
5
|
+
def retrieve_and_generate(
|
|
6
|
+
keyword: str,
|
|
7
|
+
language: str = None,
|
|
8
|
+
owner: str = None,
|
|
9
|
+
stars: str = None,
|
|
10
|
+
max_results: int = 100,
|
|
11
|
+
num_top: int = 3
|
|
12
|
+
) -> dict:
|
|
13
|
+
"""
|
|
14
|
+
Retrieve GitHub repositories based on search parameters, perform neural ranking,
|
|
15
|
+
and generate a final response using a generative model.
|
|
16
|
+
|
|
17
|
+
Parameters:
|
|
18
|
+
- keyword: Base search keyword.
|
|
19
|
+
- language: (Optional) Filter by programming language.
|
|
20
|
+
- owner: (Optional) Restrict search to a specific repository owner.
|
|
21
|
+
- stars: (Optional) Filter by stars (e.g., ">100", "<50").
|
|
22
|
+
- max_results: Maximum number of repositories to retrieve.
|
|
23
|
+
- num_top: Number of top results to use for generation.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
A dictionary with the built query, top-ranked results, and generated response.
|
|
27
|
+
"""
|
|
28
|
+
qualifiers = {}
|
|
29
|
+
if language:
|
|
30
|
+
qualifiers["language"] = language
|
|
31
|
+
if owner:
|
|
32
|
+
qualifiers["user"] = owner
|
|
33
|
+
if stars:
|
|
34
|
+
qualifiers["stars"] = stars
|
|
35
|
+
|
|
36
|
+
query = build_query(keyword, qualifiers)
|
|
37
|
+
repo_results = search_repositories_with_cache(query, max_results=max_results)
|
|
38
|
+
if not repo_results:
|
|
39
|
+
return {"error": "No results found."}
|
|
40
|
+
ranked_repos = neural_rank_repositories(repo_results, keyword)
|
|
41
|
+
generated_response = generate_response_from_results(keyword, ranked_repos, num_results=num_top)
|
|
42
|
+
return {
|
|
43
|
+
"query": query,
|
|
44
|
+
"results": ranked_repos[:10],
|
|
45
|
+
"generated_response": generated_response
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
def retrieve_and_generate_df(
|
|
49
|
+
keyword: str,
|
|
50
|
+
language: str = None,
|
|
51
|
+
owner: str = None,
|
|
52
|
+
stars: str = None,
|
|
53
|
+
max_results: int = 100,
|
|
54
|
+
num_top: int = 3
|
|
55
|
+
) -> DataFrame:
|
|
56
|
+
"""
|
|
57
|
+
Return the top repository results as a pandas DataFrame.
|
|
58
|
+
"""
|
|
59
|
+
data = retrieve_and_generate(keyword, language, owner, stars, max_results, num_top)
|
|
60
|
+
if "error" in data:
|
|
61
|
+
return DataFrame()
|
|
62
|
+
from pandas import DataFrame
|
|
63
|
+
return DataFrame(data["results"])
|
|
File without changes
|
ab/rag/config/config.py
ADDED
ab/rag/main.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# For running the application from the command line (local testing)
|
|
2
|
+
from api import retrieve_and_generate
|
|
3
|
+
|
|
4
|
+
if __name__ == "__main__":
|
|
5
|
+
keyword = input("Enter search keyword: ").strip()
|
|
6
|
+
language = input("Filter by language (press enter to skip): ").strip() or None
|
|
7
|
+
owner = input("Restrict search to a specific owner (press enter to skip): ").strip() or None
|
|
8
|
+
stars = input("Filter by stars (e.g., >100, <50) (press enter to skip): ").strip() or None
|
|
9
|
+
|
|
10
|
+
result = retrieve_and_generate(keyword, language, owner, stars)
|
|
11
|
+
|
|
12
|
+
if "error" in result:
|
|
13
|
+
print("Error:", result["error"])
|
|
14
|
+
else:
|
|
15
|
+
print("\nFinal Generated Response:")
|
|
16
|
+
print(result.get("generated_response"))
|
|
17
|
+
print("\nTop Ranked Repositories:")
|
|
18
|
+
for repo in result.get("results", []):
|
|
19
|
+
print(f"{repo['full_name']} - {repo['stars']} stars - Neural Score: {repo['neural_score']:.4f} - URL: {repo['url']}")
|
ab/rag/utils/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import shelve
|
|
3
|
+
from github import Github, Auth, RateLimitExceededException, GithubException
|
|
4
|
+
from config.config import GITHUB_TOKEN, CACHE_FILE
|
|
5
|
+
|
|
6
|
+
# Create a GitHub instance using the token from config
|
|
7
|
+
g = Github(auth=Auth.Token(GITHUB_TOKEN))
|
|
8
|
+
|
|
9
|
+
def wait_for_rate_limit():
|
|
10
|
+
core_limit = g.get_rate_limit().core
|
|
11
|
+
reset_timestamp = core_limit.reset.timestamp()
|
|
12
|
+
current_timestamp = time.time()
|
|
13
|
+
wait_time = reset_timestamp - current_timestamp + 5 # extra buffer
|
|
14
|
+
print(f"Rate limit exceeded. Waiting for {wait_time:.0f} seconds...")
|
|
15
|
+
time.sleep(wait_time)
|
|
16
|
+
|
|
17
|
+
def build_query(base_keyword: str, qualifiers: dict) -> str:
|
|
18
|
+
query = f"{base_keyword} in:readme in:description"
|
|
19
|
+
for key, value in qualifiers.items():
|
|
20
|
+
if value:
|
|
21
|
+
query += f" {key}:{value}"
|
|
22
|
+
return query
|
|
23
|
+
|
|
24
|
+
def search_repositories_with_cache(query: str, max_results: int = 100) -> list[dict]:
|
|
25
|
+
with shelve.open(CACHE_FILE) as cache:
|
|
26
|
+
if query in cache:
|
|
27
|
+
print("Using cached repository results.")
|
|
28
|
+
return cache[query]
|
|
29
|
+
else:
|
|
30
|
+
while True:
|
|
31
|
+
try:
|
|
32
|
+
repos = g.search_repositories(query, sort="stars", order="desc")
|
|
33
|
+
break
|
|
34
|
+
except RateLimitExceededException:
|
|
35
|
+
wait_for_rate_limit()
|
|
36
|
+
except GithubException as e:
|
|
37
|
+
print("GitHub Exception:", e)
|
|
38
|
+
return []
|
|
39
|
+
repo_list = []
|
|
40
|
+
count = 0
|
|
41
|
+
for repo in repos:
|
|
42
|
+
repo_list.append({
|
|
43
|
+
"full_name": repo.full_name,
|
|
44
|
+
"stars": repo.stargazers_count,
|
|
45
|
+
"url": repo.html_url,
|
|
46
|
+
"description": repo.description or ""
|
|
47
|
+
})
|
|
48
|
+
count += 1
|
|
49
|
+
if count >= max_results:
|
|
50
|
+
break
|
|
51
|
+
cache[query] = repo_list
|
|
52
|
+
return repo_list
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import logging
|
|
3
|
+
from sentence_transformers import SentenceTransformer
|
|
4
|
+
from sklearn.metrics.pairwise import cosine_similarity
|
|
5
|
+
from transformers import pipeline
|
|
6
|
+
from config.config import MODEL_NAME, GENERATOR_MODEL
|
|
7
|
+
|
|
8
|
+
logging.basicConfig(level=logging.INFO)
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
model = SentenceTransformer(MODEL_NAME)
|
|
12
|
+
generator = pipeline("text-generation", model=GENERATOR_MODEL)
|
|
13
|
+
|
|
14
|
+
def neural_rank_repositories(repo_results: list[dict], search_query: str) -> list[dict]:
|
|
15
|
+
logger.info("Starting neural ranking for query: '%s'", search_query)
|
|
16
|
+
start_time = time.time()
|
|
17
|
+
query_embedding = model.encode([search_query])
|
|
18
|
+
texts = [f"{repo['full_name']}. {repo['description']}" for repo in repo_results]
|
|
19
|
+
embeddings = model.encode(texts)
|
|
20
|
+
similarities = cosine_similarity(query_embedding, embeddings)[0]
|
|
21
|
+
for repo, score in zip(repo_results, similarities):
|
|
22
|
+
repo["neural_score"] = score
|
|
23
|
+
ranked = sorted(repo_results, key=lambda x: x["neural_score"], reverse=True)
|
|
24
|
+
elapsed = time.time() - start_time
|
|
25
|
+
logger.info("Neural ranking completed in %.2f seconds.", elapsed)
|
|
26
|
+
return ranked
|
|
27
|
+
|
|
28
|
+
def generate_response_from_results(
|
|
29
|
+
search_query: str,
|
|
30
|
+
ranked_results: list[dict],
|
|
31
|
+
num_results: int = 3,
|
|
32
|
+
temperature: float = 0.6,
|
|
33
|
+
top_k: int = 40,
|
|
34
|
+
top_p: float = 0.8,
|
|
35
|
+
max_new_tokens: int = 120
|
|
36
|
+
) -> str:
|
|
37
|
+
"""
|
|
38
|
+
Build a detailed prompt from the top-ranked results and generate a final response using
|
|
39
|
+
the generative model. The prompt now instructs the model to provide:
|
|
40
|
+
- A concise technical summary on implementing dynamic filtering.
|
|
41
|
+
- A simple pseudo-code example.
|
|
42
|
+
- Key design decisions highlighted.
|
|
43
|
+
|
|
44
|
+
Generation parameters are adjusted for a bit less randomness (lower temperature) and
|
|
45
|
+
more focused sampling (top_k, top_p).
|
|
46
|
+
"""
|
|
47
|
+
context = f"Search Query: {search_query}\n\nTop relevant repositories:\n"
|
|
48
|
+
for repo in ranked_results[:num_results]:
|
|
49
|
+
context += (
|
|
50
|
+
f"- {repo['full_name']} (Stars: {repo['stars']})\n"
|
|
51
|
+
f" Description: {repo['description']}\n"
|
|
52
|
+
f" URL: {repo['url']}\n\n"
|
|
53
|
+
)
|
|
54
|
+
# Updated prompt instructing for a concise summary and pseudo-code
|
|
55
|
+
context += (
|
|
56
|
+
"Based on the above information, provide a concise technical summary that explains "
|
|
57
|
+
"how one might implement dynamic filtering in a software project. Include a simple pseudo-code "
|
|
58
|
+
"example and explicitly mention key design decisions (such as choice of data structures, performance considerations, "
|
|
59
|
+
"and modular design)."
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Log prompt length for debugging
|
|
63
|
+
logger.info("Prompt built with length: %d characters", len(context))
|
|
64
|
+
|
|
65
|
+
response = generator(
|
|
66
|
+
context,
|
|
67
|
+
max_new_tokens=max_new_tokens,
|
|
68
|
+
truncation=True,
|
|
69
|
+
do_sample=True,
|
|
70
|
+
temperature=temperature,
|
|
71
|
+
top_k=top_k,
|
|
72
|
+
top_p=top_p
|
|
73
|
+
)[0]['generated_text']
|
|
74
|
+
|
|
75
|
+
return response
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nn-rag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Neural Retrieval-Augmented Generation for GitHub Search
|
|
5
|
+
Home-page: https://github.com/ABrain-One/nn-rag
|
|
6
|
+
Author: ABrain One and contributors
|
|
7
|
+
Author-email: AI@ABrain.one
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.6
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: PyGithub>=1.55
|
|
14
|
+
Requires-Dist: sentence-transformers>=2.2.2
|
|
15
|
+
Requires-Dist: scikit-learn>=1.0.2
|
|
16
|
+
Requires-Dist: transformers>=4.26.1
|
|
17
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
18
|
+
Requires-Dist: pandas>=1.5.3
|
|
19
|
+
Requires-Dist: dotenv
|
|
20
|
+
Dynamic: author
|
|
21
|
+
Dynamic: author-email
|
|
22
|
+
Dynamic: classifier
|
|
23
|
+
Dynamic: home-page
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
Dynamic: requires-dist
|
|
26
|
+
Dynamic: requires-python
|
|
27
|
+
Dynamic: summary
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
ab/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
ab/rag/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
ab/rag/api.py,sha256=btrr2dbhalla3SnCt4fo6W7YSeYCii9KBSS6aBcmoyg,2167
|
|
4
|
+
ab/rag/main.py,sha256=8nt3yL9S7TuWzBp2sdQ5ZJxuQHez_XaVck1fFmVIR2A,932
|
|
5
|
+
ab/rag/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
ab/rag/config/config.py,sha256=Z_MHMn4t-seV5yHexTuSQCDXzh_uhzG4gi3n0i2iPxY,215
|
|
7
|
+
ab/rag/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
ab/rag/utils/github_utils.py,sha256=MFfrz1wJZOQ07z85SrhN37eeEruE5bd7ZTJVYRBAAOk,1939
|
|
9
|
+
ab/rag/utils/neural_utils.py,sha256=NcdhMiuuNWnM5XX61MWVqQyAclYC9LpPwx-Y0B3NBtY,2986
|
|
10
|
+
nn_rag-0.1.0.dist-info/licenses/LICENSE,sha256=vwgbuMjj85Gfn2o4Iax-QO8tw2wm10awp4PbfG3xryI,1106
|
|
11
|
+
nn_rag-0.1.0.dist-info/METADATA,sha256=OOMR0HocRdVq74oTaCMZZbeilrRr7yREXRvctxF6d8g,814
|
|
12
|
+
nn_rag-0.1.0.dist-info/WHEEL,sha256=1tXe9gY0PYatrMPMDd6jXqjfpz_B-Wqm32CPfRC58XU,91
|
|
13
|
+
nn_rag-0.1.0.dist-info/top_level.txt,sha256=pj2AFNuokTRbMBdN8rKlfvu2W0-fCbmPJF0bMZInfs4,3
|
|
14
|
+
nn_rag-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024- ABrain One and contributors
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ab
|