Spaces:
Runtime error
Runtime error
import tinydb | |
import gradio as gr | |
db = tinydb.TinyDB("books.json") | |
table = db.table("books") | |
def add_book(title, author): | |
# Create a dictionary to store the book information | |
book = {"title": title, "author": author} | |
# Insert the book into the table | |
table.insert(book) | |
# Return a confirmation message | |
return f"Added {title} by {author} to the database." | |
def get_books_by_title(title): | |
# Query the database to get books with the specified title | |
books = table.search(tinydb.where("title") == title) | |
# Format the books as a string for display | |
books_str = "\n".join([f"{book['title']} by {book['author']}" for book in books]) | |
return books_str | |
def update_author_by_title(title, new_author): | |
# Fetch the existing author for the book | |
existing_author = table.search(tinydb.where("title") == title)[0].get("author") | |
# Update the author of the book with the specified title | |
table.update({"author": new_author}, tinydb.where("title") == title) | |
return f"Updated author for the book '{title}' from '{existing_author}' to '{new_author}'." | |
def process_data(option, title, author): | |
if option == "Insert": | |
return add_book(title, author) | |
elif option == "Fetch": | |
if title: | |
return get_books_by_title(title) | |
else: | |
return get_all_books() | |
elif option == "Update": | |
if title and author: | |
return update_author_by_title(title, author) | |
else: | |
return "Title and author are required for update." | |
else: | |
return "Invalid option" | |
demo = gr.Interface( | |
fn=process_data, | |
inputs=[ | |
gr.Radio(["Insert", "Fetch", "Update"], label="Select Operation"), | |
gr.Textbox(label="Title"), | |
gr.Textbox(label="Author"), | |
], | |
outputs=gr.Textbox(label="Result") | |
) | |
demo.launch() |