Spaces:
Running
Running
File size: 5,919 Bytes
7dc78b3 f126864 7dc78b3 0955e72 7dc78b3 f126864 0955e72 f126864 797c083 f126864 c6fe03c dce5b39 f126864 0955e72 f126864 0955e72 7dc78b3 0955e72 7dc78b3 0955e72 7dc78b3 0955e72 f126864 0955e72 7dc78b3 92dd823 f126864 0955e72 f126864 0955e72 f126864 0955e72 c6fe03c 0955e72 c6fe03c 0955e72 f126864 0955e72 c6fe03c 0955e72 c6fe03c 0955e72 c6fe03c 0955e72 c6fe03c 0955e72 f126864 7dc78b3 f126864 0955e72 7dc78b3 0955e72 457a71b 0955e72 7dc78b3 0955e72 |
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 |
import gradio as gr
import os
import json
import subprocess
import dotenv
import shutil
import uuid
from schemas import Response
from openai import OpenAI
from pathlib import Path
from pymilvus import MilvusClient, model
from repo2txt import make_tree
from utils import copy_search_results, create_documentation_string, choice_prompt
_ = dotenv.load_dotenv()
subprocess.run(["python3", "scripts/make_docs.py"])
subprocess.run(["python3", "scripts/make_rag_db.py"])
client = MilvusClient("milvus.db")
embedding_fn = model.dense.OpenAIEmbeddingFunction(
model_name="text-embedding-3-large",
api_key=os.environ.get("OPENAI_API_KEY"),
dimensions=3072,
)
oai_client = OpenAI()
def list_huggingface_resources_names() -> list[str]:
"""List all the names of the libraries, services, and other resources available within the HuggingFace ecosystem.
Returns:
A list of libraries, services, and other resources available within the HuggingFace ecosystem
"""
with open("repos_config.json", "r") as f:
repos = json.load(f)
return [repo["title"] for repo in repos]
def search_documents(query, resource_names=None, topk=50):
"""Search for relevant documents in the Milvus database."""
query_vectors = embedding_fn.encode_queries([query])
search_params = {
"collection_name": "hf_docs",
"data": query_vectors,
"limit": topk,
"output_fields": ["text", "file_path", "resource"],
}
if resource_names:
if len(resource_names) == 1:
search_params["filter"] = f"resource == '{resource_names[0]}'"
else:
resource_list = "', '".join(resource_names)
search_params["filter"] = f"resource in ['{resource_list}']"
return client.search(**search_params)
def get_huggingface_documentation(topic: str, resource_names: list[str] = []) -> str:
"""Get the documentation for the given topic and resource names.
Args:
topic: Focus the docs on a specific topic (e.g. "Anthropic Provider Chat UI", "LoRA methods PEFT" or "TGI on Intel GPUs")
resource_names: A list of relevant resource names to the topic. Must be as specific as possible. Empty list means all resources.
Returns:
A string of documentation for the given topic and resource names
"""
try:
# Search for relevant documents
query_vectors = embedding_fn.encode_queries([topic])
search_params = {
"collection_name": "hf_docs",
"data": query_vectors,
"limit": 50,
"output_fields": ["text", "file_path", "resource"],
}
if resource_names:
if len(resource_names) == 1:
search_params["filter"] = f"resource == '{resource_names[0]}'"
else:
resource_list = "', '".join(resource_names)
search_params["filter"] = f"resource in ['{resource_list}']"
search_results = client.search(**search_params)
# Create temporary folder and copy files
temp_folder = str(uuid.uuid4())
copy_search_results(search_results, temp_folder)
# Generate directory tree
tree_structure = make_tree(Path(temp_folder) / "docs")
# Get relevant file IDs using GPT-4
response = oai_client.responses.parse(
model="gpt-4o",
input=[
{
"role": "user",
"content": choice_prompt.substitute(
question=topic, tree_structure=tree_structure
),
}
],
text_format=Response,
)
file_id = response.output_parsed.file_id
print(f"{topic} -> {file_id}")
# Create the documentation string using the file IDs and template
documentation_string = create_documentation_string([file_id], temp_folder)
# Clean up temporary folder
shutil.rmtree(temp_folder, ignore_errors=True)
return documentation_string
except Exception as e:
return f"Error generating documentation: {str(e)}"
def load_readme() -> str:
"""Load and return the README content, skipping YAML frontmatter."""
try:
with open("README.md", "r", encoding="utf-8") as f:
content = f.read()
# Skip YAML frontmatter if it exists
lines = content.split("\n")
start_index = 0
if content.startswith("---"):
# Find the second '---' line to skip frontmatter
dash_count = 0
for i, line in enumerate(lines):
if line.strip() == "---":
dash_count += 1
if dash_count == 2:
start_index = i + 1
break
# Find the line that starts with "### The Problem: Your LLM is stuck in the past"
for i in range(start_index, len(lines)):
if lines[i].startswith("### The Problem: Your LLM is stuck in the past"):
start_index = i
break
# Join the lines from the target starting point
content = "\n".join(lines[start_index:])
return content
except FileNotFoundError:
return "README.md not found"
list_resources_demo = gr.Interface(
fn=list_huggingface_resources_names,
inputs=[],
outputs="json",
)
get_docs_demo = gr.Interface(
fn=get_huggingface_documentation,
inputs=["text", "json"],
outputs="text",
)
# Create README tab with Markdown component
with gr.Blocks() as readme_tab:
gr.Markdown(load_readme())
# Create tabbed interface
demo = gr.TabbedInterface(
[readme_tab, list_resources_demo, get_docs_demo],
["Quickstart", "List Resources", "Get Documentation"],
title="Open HFContext7 MCP - Up-to-date 🤗 Docs For Any Prompt",
)
demo.launch(mcp_server=True)
|