Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,57 @@
|
|
1 |
-
import
|
|
|
2 |
|
3 |
-
|
4 |
-
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
)
|
11 |
-
|
|
|
|
1 |
+
import tinydb
|
2 |
+
import gradio as gr
|
3 |
|
4 |
+
db = tinydb.TinyDB("books.json")
|
5 |
+
table = db.table("books")
|
6 |
|
7 |
+
def add_book(title, author):
|
8 |
+
# Create a dictionary to store the book information
|
9 |
+
book = {"title": title, "author": author}
|
10 |
+
# Insert the book into the table
|
11 |
+
table.insert(book)
|
12 |
+
# Return a confirmation message
|
13 |
+
return f"Added {title} by {author} to the database."
|
14 |
+
|
15 |
+
def get_books_by_title(title):
|
16 |
+
# Query the database to get books with the specified title
|
17 |
+
books = table.search(tinydb.where("title") == title)
|
18 |
+
# Format the books as a string for display
|
19 |
+
books_str = "\n".join([f"{book['title']} by {book['author']}" for book in books])
|
20 |
+
return books_str
|
21 |
+
|
22 |
+
def update_author_by_title(title, new_author):
|
23 |
+
# Fetch the existing author for the book
|
24 |
+
existing_author = table.search(tinydb.where("title") == title)[0].get("author")
|
25 |
+
|
26 |
+
# Update the author of the book with the specified title
|
27 |
+
table.update({"author": new_author}, tinydb.where("title") == title)
|
28 |
+
|
29 |
+
return f"Updated author for the book '{title}' from '{existing_author}' to '{new_author}'."
|
30 |
+
|
31 |
+
def process_data(option, title, author):
|
32 |
+
if option == "Insert":
|
33 |
+
return add_book(title, author)
|
34 |
+
elif option == "Fetch":
|
35 |
+
if title:
|
36 |
+
return get_books_by_title(title)
|
37 |
+
else:
|
38 |
+
return get_all_books()
|
39 |
+
elif option == "Update":
|
40 |
+
if title and author:
|
41 |
+
return update_author_by_title(title, author)
|
42 |
+
else:
|
43 |
+
return "Title and author are required for update."
|
44 |
+
else:
|
45 |
+
return "Invalid option"
|
46 |
+
|
47 |
+
demo = gr.Interface(
|
48 |
+
fn=process_data,
|
49 |
+
inputs=[
|
50 |
+
gr.Radio(["Insert", "Fetch", "Update"], label="Select Operation"),
|
51 |
+
gr.Textbox(label="Title"),
|
52 |
+
gr.Textbox(label="Author"),
|
53 |
+
],
|
54 |
+
outputs=gr.Textbox(label="Result")
|
55 |
)
|
56 |
+
|
57 |
+
demo.launch()
|