useful-lists / app.py
ghost613's picture
Update app.py
e71c01b verified
import gradio as gr
import os
import json
import glob
import pandas as pd
# Directory to store JSON list files
LISTS_DIR = "lists"
# Ensure the lists directory exists
os.makedirs(LISTS_DIR, exist_ok=True)
# Get list of available JSON files
def get_list_files():
files = glob.glob(os.path.join(LISTS_DIR, "*.json"))
return [os.path.basename(f)[:-5] for f in files] # Remove .json extension
# Load data from a JSON file
def load_list_data(list_name):
file_path = os.path.join(LISTS_DIR, f"{list_name}.json")
if os.path.exists(file_path):
with open(file_path, "r") as f:
return json.load(f)
return {"name": "Empty List", "items": []}
# Create HTML table with clickable links
def get_list_items_html(list_name):
data = load_list_data(list_name)
html = "<table style='width:100%; border-collapse: collapse;'>"
html += "<tr><th style='text-align:left; padding:8px; border-bottom:1px solid #ddd;'>Name</th>"
html += "<th style='text-align:left; padding:8px; border-bottom:1px solid #ddd;'>Description</th>"
html += "<th style='text-align:left; padding:8px; border-bottom:1px solid #ddd;'>Link</th></tr>"
for item in data["items"]:
html += "<tr>"
html += f"<td style='padding:8px; border-bottom:1px solid #ddd;'>{item['name']}</td>"
html += f"<td style='padding:8px; border-bottom:1px solid #ddd;'>{item['description']}</td>"
html += f"<td style='padding:8px; border-bottom:1px solid #ddd;'><a href='{item['link']}' target='_blank'>{item['link']}</a></td>"
html += "</tr>"
html += "</table>"
return html
# Get list items in table format (for backup/alternative view)
def get_list_items(list_name):
data = load_list_data(list_name)
return [[item["name"], item["description"], item["link"]]
for item in data["items"]]
# Get list title
def get_list_title(list_name):
data = load_list_data(list_name)
return data["name"]
# Function to switch between lists
def switch_list(list_name):
return get_list_title(list_name), get_list_items_html(list_name)
# Build the Gradio interface
with gr.Blocks(title="Useful Things Archive") as app:
gr.Markdown("""
## Useful Things Archive
""")
# Get available lists
list_names = get_list_files()
if not list_names:
list_names = ["learn"] # Fallback to default
# Current list state
current_list = gr.State(value=list_names[0])
with gr.Row():
# Create tabs for each list
with gr.Tabs() as tabs:
tab_list = []
for list_name in list_names:
tab = gr.Tab(label=get_list_title(list_name))
tab_list.append((tab, list_name))
list_title = gr.Markdown(f"## {get_list_title(list_names[0])}")
# Use HTML component instead of Dataframe to enable clickable links
items_html = gr.HTML(value=get_list_items_html(list_names[0]))
# Connect tab events to switch lists
for i, (tab, list_name) in enumerate(tab_list):
tab.select(
lambda name=list_name: switch_list(name),
inputs=[],
outputs=[list_title, items_html]
)
# Launch the app
app.launch()