Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
from langchain_community.retrievers import WikipediaRetriever
|
4 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
5 |
+
from langchain.schema import HumanMessage, SystemMessage
|
6 |
+
import gradio as gr
|
7 |
+
import re
|
8 |
+
|
9 |
+
# Load environment variables
|
10 |
+
load_dotenv()
|
11 |
+
|
12 |
+
# Get the API key from the environment variable
|
13 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
14 |
+
|
15 |
+
if not api_key:
|
16 |
+
raise ValueError("GOOGLE_API_KEY environment variable is not set")
|
17 |
+
|
18 |
+
os.environ["GOOGLE_API_KEY"] = api_key
|
19 |
+
|
20 |
+
# Initiate WikipediaRetriever
|
21 |
+
retriever = WikipediaRetriever()
|
22 |
+
|
23 |
+
# Initiate chat model
|
24 |
+
chat_model = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.2)
|
25 |
+
|
26 |
+
# Function to get book info from Wikipedia
|
27 |
+
def get_book_info(title, author):
|
28 |
+
query = f"{title} book by {author}"
|
29 |
+
docs = retriever.get_relevant_documents(query)
|
30 |
+
if docs:
|
31 |
+
return docs[0].page_content
|
32 |
+
return None
|
33 |
+
|
34 |
+
# Function to extract book info
|
35 |
+
def extract_book_info(book_content):
|
36 |
+
messages = [
|
37 |
+
SystemMessage(content="You are an AI assistant who is an expert in analyzing and recommending books."),
|
38 |
+
HumanMessage(content=f"""
|
39 |
+
Based on the following information about this book:
|
40 |
+
{book_content}
|
41 |
+
|
42 |
+
Please provide these details using the following format, only using information already available to you.
|
43 |
+
Do not use asterisks or any other markdown formatting:
|
44 |
+
|
45 |
+
1. Genre/Subject: [genre or subject of this book]
|
46 |
+
2. Synopsis (within 100 words maximum): [synopsis of this book]
|
47 |
+
3. Book Recommendations:
|
48 |
+
- [Title of Recommended Book 1]: [brief explanation within 20 words maximum]
|
49 |
+
- [Title of Recommended Book 2]: [brief explanation within 20 words maximum]
|
50 |
+
- [Title of Recommended Book 3]: [brief explanation within 20 words maximum]
|
51 |
+
- [Title of Recommended Book 4]: [brief explanation within 20 words maximum]
|
52 |
+
- [Title of Recommended Book 5]: [brief explanation within 20 words maximum]
|
53 |
+
|
54 |
+
If the information you have is not enough to provide recommendations, give the available information and state that you cannot give recommendations due to lack of information.
|
55 |
+
""")
|
56 |
+
]
|
57 |
+
|
58 |
+
response = chat_model(messages)
|
59 |
+
return response.content
|
60 |
+
|
61 |
+
# Function to ask other questions
|
62 |
+
def chat_about_book(book_content, question):
|
63 |
+
messages = [
|
64 |
+
SystemMessage(content=f"""You are an AI assistant who is an expert on this book:\n{book_content}
|
65 |
+
Answer the questions about this book using only informations already available to you.
|
66 |
+
Also, do not bold any of the text"""),
|
67 |
+
HumanMessage(content=question)
|
68 |
+
]
|
69 |
+
|
70 |
+
response = chat_model(messages)
|
71 |
+
return response.content
|
72 |
+
|
73 |
+
def parse_extracted_info(extracted_info):
|
74 |
+
genre = "Genre not found"
|
75 |
+
synopsis = "Synopsis not found"
|
76 |
+
recommendations = "Recommendations not found"
|
77 |
+
|
78 |
+
# Use regex to find each section
|
79 |
+
genre_match = re.search(r'1\.\s*Genre/Subject:\s*(.*?)(?=\n2\.|\Z)', extracted_info, re.DOTALL)
|
80 |
+
synopsis_match = re.search(r'2\.\s*Synopsis.*?:\s*(.*?)(?=\n3\.|\Z)', extracted_info, re.DOTALL)
|
81 |
+
recommendations_match = re.search(r'3\.\s*(?:5\s*)?Book Recommendations?:?(.*)', extracted_info, re.DOTALL)
|
82 |
+
|
83 |
+
if genre_match:
|
84 |
+
genre = genre_match.group(1).strip()
|
85 |
+
if synopsis_match:
|
86 |
+
synopsis = synopsis_match.group(1).strip()
|
87 |
+
if recommendations_match:
|
88 |
+
recommendations = recommendations_match.group(1).strip()
|
89 |
+
|
90 |
+
# Remove asterisks from recommendations
|
91 |
+
recommendations = re.sub(r'\*+', '', recommendations)
|
92 |
+
|
93 |
+
return genre, synopsis, recommendations
|
94 |
+
|
95 |
+
def process_book(title, author):
|
96 |
+
if not title or not author:
|
97 |
+
return "Book not found", "No synopsis found", "No book recommendations available"
|
98 |
+
try:
|
99 |
+
book_info = get_book_info(title, author)
|
100 |
+
if book_info:
|
101 |
+
extracted_info = extract_book_info(book_info)
|
102 |
+
genre, synopsis, recommendations = parse_extracted_info(extracted_info)
|
103 |
+
return genre, synopsis, recommendations
|
104 |
+
return "Book not found", "No synopsis found", "No book recommendations available"
|
105 |
+
except Exception as e:
|
106 |
+
print(f"Error in process_book: {str(e)}")
|
107 |
+
return f"Error: {str(e)}", "", ""
|
108 |
+
|
109 |
+
def chat(title, author, question):
|
110 |
+
if not title or not author:
|
111 |
+
return "You have not entered the book's title and author yet."
|
112 |
+
book_info = get_book_info(title, author)
|
113 |
+
if book_info:
|
114 |
+
response = chat_about_book(book_info, question)
|
115 |
+
# Remove stars from the response
|
116 |
+
response = re.sub(r'\*+', '', response)
|
117 |
+
return response
|
118 |
+
return "Book not found. Please check the title and author."
|
119 |
+
|
120 |
+
with gr.Blocks(title="Simple Book AI (Wikipedia-based)") as demo:
|
121 |
+
gr.Markdown(
|
122 |
+
"""
|
123 |
+
# Simple Book AI (Wikipedia-based)
|
124 |
+
Input the title and author(s) of the book to get the relevant information and book recommendations similar to your book. You could also ask other questions regarding your book.
|
125 |
+
"""
|
126 |
+
)
|
127 |
+
|
128 |
+
with gr.Row():
|
129 |
+
with gr.Column(scale=2):
|
130 |
+
title_input = gr.Textbox(label="Title", placeholder="Enter the book title here...")
|
131 |
+
author_input = gr.Textbox(label="Author(s)", placeholder="Enter the author's name here...")
|
132 |
+
with gr.Row():
|
133 |
+
submit_book = gr.Button("Submit")
|
134 |
+
clear_book = gr.Button("Clear")
|
135 |
+
|
136 |
+
with gr.Column(scale=3):
|
137 |
+
question_input = gr.Textbox(label="Any other questions about this book?", placeholder="Enter your question here...")
|
138 |
+
with gr.Row():
|
139 |
+
submit_question = gr.Button("Submit")
|
140 |
+
clear_question = gr.Button("Clear")
|
141 |
+
|
142 |
+
with gr.Row():
|
143 |
+
with gr.Column(scale=2):
|
144 |
+
genre_output = gr.Textbox(label="Genre")
|
145 |
+
synopsis_output = gr.Textbox(label="Synopsis", lines=5)
|
146 |
+
recommendations_output = gr.Textbox(label="Book Recommendations", lines=5)
|
147 |
+
|
148 |
+
with gr.Column(scale=3):
|
149 |
+
chat_output = gr.Textbox(label="Answer to your question", lines=10)
|
150 |
+
with gr.Row():
|
151 |
+
retry_btn = gr.Button("Retry")
|
152 |
+
clear_chat_btn = gr.Button("Clear")
|
153 |
+
|
154 |
+
def clear_book_inputs():
|
155 |
+
return "", ""
|
156 |
+
|
157 |
+
def clear_question_input():
|
158 |
+
return ""
|
159 |
+
|
160 |
+
def clear_chat():
|
161 |
+
return ""
|
162 |
+
|
163 |
+
def retry_last_question(title, author, question):
|
164 |
+
return chat(title, author, question)
|
165 |
+
|
166 |
+
submit_book.click(process_book, inputs=[title_input, author_input], outputs=[genre_output, synopsis_output, recommendations_output])
|
167 |
+
clear_book.click(clear_book_inputs, outputs=[title_input, author_input])
|
168 |
+
submit_question.click(chat, inputs=[title_input, author_input, question_input], outputs=[chat_output])
|
169 |
+
clear_question.click(clear_question_input, outputs=[question_input])
|
170 |
+
clear_chat_btn.click(clear_chat, outputs=[chat_output])
|
171 |
+
retry_btn.click(retry_last_question, inputs=[title_input, author_input, question_input], outputs=[chat_output])
|
172 |
+
|
173 |
+
demo.launch()
|