Spaces:
Runtime error
Runtime error
File size: 1,848 Bytes
0ba984d 607d357 0ba984d 607d357 0ba984d 1de9bec 0ba984d |
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 |
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() |