|
| 1 | +import os |
| 2 | +import json |
| 3 | +import faiss |
| 4 | +import numpy as np |
| 5 | +from github import Auth |
| 6 | +from github import Github |
| 7 | +from sentence_transformers import SentenceTransformer |
| 8 | +from langchain.text_splitter import RecursiveCharacterTextSplitter |
| 9 | +from langchain_community.document_loaders import DirectoryLoader |
| 10 | +from datetime import datetime, timezone |
| 11 | + |
| 12 | +# --- Configuration --- |
| 13 | +GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') |
| 14 | +# GITHUB_TOKEN = |
| 15 | +REPO_NAME = "kevoreilly/CAPEv2" |
| 16 | +DOCS_PATH = "../docs" # Path to the folder with your documentation files (e.g., .md) |
| 17 | +MODEL_NAME = 'all-MiniLM-L6-v2' # An efficient embedding model |
| 18 | + |
| 19 | +# --- File Paths for State --- |
| 20 | +INDEX_FILE = "unified_index.faiss" |
| 21 | +METADATA_FILE = "metadata.json" |
| 22 | +TEXTS_FILE = "all_texts.json" |
| 23 | +STATE_FILE = "kb_state.json" |
| 24 | + |
| 25 | +# init pandoc |
| 26 | +# from pypandoc.pandoc_download import download_pandoc |
| 27 | +# download_pandoc() |
| 28 | + |
| 29 | +# --- Initialization --- |
| 30 | +auth = Auth.Token(GITHUB_TOKEN) |
| 31 | +g = Github(auth=auth) |
| 32 | +# auth=github.Auth.Token(...) |
| 33 | +repo = g.get_repo(REPO_NAME) |
| 34 | +model = SentenceTransformer(MODEL_NAME) |
| 35 | + |
| 36 | +# --- Load Existing Knowledge Base or Initialize a New One --- |
| 37 | +if os.path.exists(INDEX_FILE): |
| 38 | + print("Loading existing knowledge base...") |
| 39 | + index = faiss.read_index(INDEX_FILE) |
| 40 | + with open(METADATA_FILE, "r") as f: |
| 41 | + metadata = json.load(f) |
| 42 | + with open(TEXTS_FILE, "r") as f: |
| 43 | + all_texts = json.load(f) |
| 44 | + with open(STATE_FILE, "r") as f: |
| 45 | + last_update_time = datetime.fromisoformat(json.load(f)) |
| 46 | + print(f"Knowledge base loaded. Last update was at: {last_update_time}") |
| 47 | + new_issues = repo.get_issues(state='all', since=last_update_time, sort='created', direction='asc') |
| 48 | +else: |
| 49 | + print("No existing knowledge base found. Creating a new one.") |
| 50 | + index = None |
| 51 | + metadata = [] |
| 52 | + all_texts = [] |
| 53 | + # Set a very old date to fetch all issues for the first time |
| 54 | + last_update_time = datetime(1970, 1, 1, tzinfo=timezone.utc) |
| 55 | + new_issues = repo.get_issues(state='all', sort='updated', direction='asc') |
| 56 | + # Initial processing of documentation (only on first build) |
| 57 | + print("Processing documentation for the first time...") |
| 58 | + loader = DirectoryLoader(DOCS_PATH, glob="**/*.rst") |
| 59 | + docs = loader.load() |
| 60 | + text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100) |
| 61 | + doc_chunks = text_splitter.split_documents(docs) |
| 62 | + for chunk in doc_chunks: |
| 63 | + all_texts.append(chunk.page_content) |
| 64 | + metadata.append({'source': 'documentation', 'file': chunk.metadata.get('source', 'N/A')}) |
| 65 | + |
| 66 | +# --- Process GitHub Issues --- |
| 67 | +# --- Fetch New Issues from GitHub --- |
| 68 | +print(f"Fetching issues updated since {last_update_time.isoformat()}...") |
| 69 | +# The 'since' parameter fetches issues updated on or after the given time |
| 70 | +# be aware since might not work |
| 71 | + |
| 72 | +new_issue_texts = [] |
| 73 | +new_issue_metadata = [] |
| 74 | +latest_issue_time = last_update_time |
| 75 | +existing_issue_urls = {m['url'] for m in metadata if m.get('source') == 'issue'} |
| 76 | + |
| 77 | +for issue in new_issues: |
| 78 | + # We check the updated_at time to ensure we save the most recent timestamp |
| 79 | + # ToDo this doesn't work properly |
| 80 | + #if issue.updated_at.replace(tzinfo=timezone.utc) > latest_issue_time: |
| 81 | + # latest_issue_time = issue.updated_at.replace(tzinfo=timezone.utc) |
| 82 | + |
| 83 | + # Simple logic to avoid adding duplicates. For a robust system, you might check IDs. |
| 84 | + issue_url = issue.html_url |
| 85 | + if issue_url in existing_issue_urls: |
| 86 | + print(f"Skipping issue #{issue.number} as it might be a duplicate or minor update.") |
| 87 | + continue |
| 88 | + |
| 89 | + print(f"Processing new/updated issue #{issue.number}") |
| 90 | + full_text = f"Title: {issue.title}\nBody: {issue.body}" |
| 91 | + for comment in issue.get_comments(): |
| 92 | + full_text += f"\nComment: {comment.body}" |
| 93 | + |
| 94 | + new_issue_texts.append(full_text) |
| 95 | + new_issue_metadata.append({'source': 'issue', 'number': issue.number, 'url': issue.html_url}) |
| 96 | + |
| 97 | +# --- Add New Issues to the Knowledge Base --- |
| 98 | +if new_issue_texts: |
| 99 | + print(f"Found {len(new_issue_texts)} new/updated issues to add.") |
| 100 | + |
| 101 | + # Generate embeddings for new issues only |
| 102 | + new_embeddings = model.encode(new_issue_texts, show_progress_bar=True) |
| 103 | + new_embeddings = np.array(new_embeddings).astype('float32') |
| 104 | + |
| 105 | + # If the index is new, create it |
| 106 | + if index is None: |
| 107 | + dimension = new_embeddings.shape[1] |
| 108 | + index = faiss.IndexFlatL2(dimension) |
| 109 | + |
| 110 | + # Add new embeddings to the index and update metadata lists |
| 111 | + index.add(new_embeddings) |
| 112 | + all_texts.extend(new_issue_texts) |
| 113 | + metadata.extend(new_issue_metadata) |
| 114 | + |
| 115 | + print("Knowledge base updated.") |
| 116 | +else: |
| 117 | + print("No new issues found. Knowledge base is already up-to-date.") |
| 118 | + |
| 119 | +# --- Save the Updated Knowledge Base and State --- |
| 120 | +print("Saving knowledge base and state...") |
| 121 | +faiss.write_index(index, INDEX_FILE) |
| 122 | +with open(METADATA_FILE, "w") as f: |
| 123 | + json.dump(metadata, f, indent=2) |
| 124 | +with open(TEXTS_FILE, "w") as f: |
| 125 | + json.dump(all_texts, f, indent=2) |
| 126 | +# Save the timestamp of the latest issue we processed for the next run |
| 127 | +with open(STATE_FILE, "w") as f: |
| 128 | + json.dump(latest_issue_time.isoformat(), f) |
| 129 | + |
| 130 | +print("Process complete!") |
0 commit comments