Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| WIKI_DIR = "wiki" | |
| def list_articles(): | |
| if not os.path.exists(WIKI_DIR): | |
| return [] | |
| return sorted([ | |
| f[:-3] | |
| for f in os.listdir(WIKI_DIR) | |
| if f.endswith(".md") | |
| ]) | |
| def load_article(article_name): | |
| if not article_name: | |
| return "# Huggingpedia\n\nSelect an article." | |
| path = os.path.join(WIKI_DIR, f"{article_name}.md") | |
| if not os.path.exists(path): | |
| return "# Article Not Found" | |
| with open(path, "r", encoding="utf-8") as f: | |
| return f.read() | |
| def search_articles(query): | |
| articles = list_articles() | |
| if not query.strip(): | |
| return articles | |
| query = query.lower() | |
| results = [] | |
| for article in articles: | |
| score = 0 | |
| if query in article.lower(): | |
| score += 100 | |
| path = os.path.join(WIKI_DIR, f"{article}.md") | |
| try: | |
| with open(path, "r", encoding="utf-8") as f: | |
| content = f.read().lower() | |
| if query in content: | |
| score += 10 | |
| except Exception: | |
| pass | |
| if score > 0: | |
| results.append((score, article)) | |
| results.sort(reverse=True) | |
| return [article for _, article in results] | |
| def select_first_article(results): | |
| if not results: | |
| return None, "# No results found" | |
| article = results[0] | |
| return article, load_article(article) | |
| with gr.Blocks(title="Huggingpedia") as demo: | |
| gr.Markdown("# ๐ Huggingpedia") | |
| gr.Markdown("Search and browse encyclopedia articles") | |
| search_box = gr.Textbox( | |
| label="Search", | |
| placeholder="Search articles..." | |
| ) | |
| article_list = gr.Dropdown( | |
| choices=list_articles(), | |
| label="Articles" | |
| ) | |
| article_content = gr.Markdown() | |
| search_box.change( | |
| fn=search_articles, | |
| inputs=search_box, | |
| outputs=article_list | |
| ) | |
| article_list.change( | |
| fn=load_article, | |
| inputs=article_list, | |
| outputs=article_content | |
| ) | |
| search_box.submit( | |
| fn=lambda q: select_first_article(search_articles(q)), | |
| inputs=search_box, | |
| outputs=[article_list, article_content] | |
| ) | |
| if list_articles(): | |
| first = list_articles()[0] | |
| demo.load( | |
| fn=lambda: (first, load_article(first)), | |
| outputs=[article_list, article_content] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |