Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,60 +1,47 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import anthropic
|
| 3 |
import PyPDF2
|
| 4 |
-
import io
|
| 5 |
import os
|
| 6 |
|
| 7 |
-
# Claude client
|
| 8 |
client = anthropic.Anthropic(api_key=os.environ.get("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"))
|
| 9 |
|
| 10 |
-
# Store uploaded book text in memory
|
| 11 |
book_storage = {}
|
| 12 |
|
| 13 |
def extract_pdf_text(pdf_file):
|
| 14 |
-
"""Extract text from PDF with page numbers"""
|
| 15 |
if pdf_file is None:
|
| 16 |
return None, "No file uploaded"
|
| 17 |
-
|
| 18 |
try:
|
| 19 |
reader = PyPDF2.PdfReader(pdf_file)
|
| 20 |
pages = []
|
| 21 |
for i, page in enumerate(reader.pages):
|
| 22 |
text = page.extract_text()
|
| 23 |
-
if text.strip():
|
| 24 |
pages.append(f"[PAGE {i+1}]\n{text}")
|
| 25 |
-
|
| 26 |
full_text = "\n\n".join(pages)
|
| 27 |
return full_text, f"β
{len(reader.pages)} pages extracted successfully!"
|
| 28 |
except Exception as e:
|
| 29 |
return None, f"β Error: {str(e)}"
|
| 30 |
|
| 31 |
-
|
| 32 |
def upload_book(book_name, pdf_file):
|
| 33 |
-
"""Admin uploads a book PDF"""
|
| 34 |
if pdf_file is None:
|
| 35 |
return "Please select a PDF file."
|
| 36 |
-
|
| 37 |
text, msg = extract_pdf_text(pdf_file)
|
| 38 |
if text:
|
| 39 |
-
book_storage[book_name] = {
|
| 40 |
-
"text": text,
|
| 41 |
-
"pages": text.count("[PAGE ")
|
| 42 |
-
}
|
| 43 |
return f"β
'{book_name}' uploaded! {msg}"
|
| 44 |
return msg
|
| 45 |
|
| 46 |
-
|
| 47 |
def ask_question(book_name, question, chat_history):
|
| 48 |
-
"""Ask question from uploaded book"""
|
| 49 |
if not question.strip():
|
| 50 |
return chat_history, ""
|
| 51 |
-
|
| 52 |
if book_name not in book_storage:
|
| 53 |
-
chat_history.append(
|
|
|
|
| 54 |
return chat_history, ""
|
| 55 |
-
|
| 56 |
book_text = book_storage[book_name]["text"]
|
| 57 |
-
|
| 58 |
system_prompt = f"""You are a sacred scripture scholar for the AI Sacred Library.
|
| 59 |
|
| 60 |
You have the TEXT of: {book_name}
|
|
@@ -62,59 +49,52 @@ You have the TEXT of: {book_name}
|
|
| 62 |
RULES:
|
| 63 |
1. Search the provided book text FIRST
|
| 64 |
2. Give EXACT original text from the book (in original language if present)
|
| 65 |
-
3. Always mention PAGE NUMBER using [PAGE X] markers
|
| 66 |
4. Provide English translation
|
| 67 |
5. Provide Tafseer/Commentary/Summary
|
| 68 |
-
6. Format response clearly
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
| 79 |
|
| 80 |
BOOK CONTENT:
|
| 81 |
{book_text[:60000]}"""
|
| 82 |
|
| 83 |
messages = []
|
| 84 |
-
for
|
| 85 |
-
messages.append({"role": "
|
| 86 |
-
messages.append({"role": "assistant", "content": assistant})
|
| 87 |
messages.append({"role": "user", "content": question})
|
| 88 |
|
| 89 |
response = client.messages.create(
|
| 90 |
-
model="claude-
|
| 91 |
max_tokens=1500,
|
| 92 |
system=system_prompt,
|
| 93 |
messages=messages
|
| 94 |
)
|
| 95 |
-
|
| 96 |
answer = response.content[0].text
|
| 97 |
-
chat_history.append(
|
|
|
|
| 98 |
return chat_history, ""
|
| 99 |
|
| 100 |
-
|
| 101 |
-
# ββ UI ββ
|
| 102 |
BOOKS = [
|
| 103 |
"Al-Quran", "Bhagavad Gita", "Holy Bible", "Torah",
|
| 104 |
"Tripitaka (Buddhism)", "The Vedas", "Guru Granth Sahib", "Avesta"
|
| 105 |
]
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
),
|
| 113 |
-
css="""
|
| 114 |
-
.gradio-container { background: #0a0a0f !important; color: #e8e0d0 !important; }
|
| 115 |
-
h1 { color: #f0e8d8 !important; text-align: center; }
|
| 116 |
-
"""
|
| 117 |
-
) as demo:
|
| 118 |
|
| 119 |
gr.Markdown("""
|
| 120 |
# π Sacred Library
|
|
@@ -124,42 +104,38 @@ with gr.Blocks(
|
|
| 124 |
""")
|
| 125 |
|
| 126 |
with gr.Tabs():
|
| 127 |
-
|
| 128 |
-
# ββ CHAT TAB ββ
|
| 129 |
with gr.Tab("π¬ Chat with Scripture"):
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
chatbot = gr.Chatbot(
|
| 139 |
label="Sacred Library AI",
|
| 140 |
height=450,
|
| 141 |
-
|
| 142 |
)
|
| 143 |
-
|
| 144 |
with gr.Row():
|
| 145 |
question_input = gr.Textbox(
|
| 146 |
-
placeholder='
|
| 147 |
label="Your Question",
|
| 148 |
scale=4
|
| 149 |
)
|
| 150 |
ask_btn = gr.Button("Ask β", variant="primary", scale=1)
|
| 151 |
-
|
| 152 |
gr.Examples(
|
| 153 |
examples=[
|
| 154 |
["Al-Quran", "Show me page 1"],
|
| 155 |
["Al-Quran", "What does Quran say about purpose of life?"],
|
| 156 |
["Bhagavad Gita", "What is karma according to Gita?"],
|
| 157 |
["Holy Bible", "Genesis chapter 1 verse 1"],
|
| 158 |
-
["Al-Quran", "What is Surah Al-Fatiha?"],
|
| 159 |
],
|
| 160 |
inputs=[book_select, question_input]
|
| 161 |
)
|
| 162 |
-
|
| 163 |
ask_btn.click(
|
| 164 |
ask_question,
|
| 165 |
inputs=[book_select, question_input, chatbot],
|
|
@@ -171,21 +147,18 @@ with gr.Blocks(
|
|
| 171 |
outputs=[chatbot, question_input]
|
| 172 |
)
|
| 173 |
|
| 174 |
-
# ββ ADMIN UPLOAD TAB ββ
|
| 175 |
with gr.Tab("π Admin β Upload Books"):
|
| 176 |
gr.Markdown("""
|
| 177 |
### Admin Book Upload Panel
|
| 178 |
Upload authentic scripture PDFs here. Users will get exact quotes from your uploaded books.
|
| 179 |
-
|
| 180 |
-
> β οΈ **Note**: In production, add password protection using `gr.State` + login check.
|
| 181 |
-
> For now, restrict this tab by keeping the Space private on Hugging Face.
|
| 182 |
""")
|
| 183 |
-
|
| 184 |
with gr.Row():
|
| 185 |
upload_book_name = gr.Dropdown(
|
| 186 |
choices=BOOKS,
|
| 187 |
value="Al-Quran",
|
| 188 |
-
label="Select Book
|
| 189 |
scale=1
|
| 190 |
)
|
| 191 |
upload_pdf = gr.File(
|
|
@@ -193,25 +166,16 @@ with gr.Blocks(
|
|
| 193 |
file_types=[".pdf"],
|
| 194 |
scale=2
|
| 195 |
)
|
| 196 |
-
|
| 197 |
upload_btn = gr.Button("π€ Upload & Index Book", variant="primary")
|
| 198 |
-
upload_status = gr.Textbox(label="
|
| 199 |
-
|
| 200 |
upload_btn.click(
|
| 201 |
upload_book,
|
| 202 |
inputs=[upload_book_name, upload_pdf],
|
| 203 |
outputs=[upload_status]
|
| 204 |
)
|
| 205 |
-
|
| 206 |
-
gr.Markdown("""
|
| 207 |
-
---
|
| 208 |
-
**Currently Indexed Books:**
|
| 209 |
-
Check the chat tab β if you can get answers from a book, it's indexed β
|
| 210 |
-
""")
|
| 211 |
|
| 212 |
-
gr.Markdown(""
|
| 213 |
-
---
|
| 214 |
-
*Sacred Library β Built with Claude AI + Gradio + PyPDF2*
|
| 215 |
-
""")
|
| 216 |
|
| 217 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import anthropic
|
| 3 |
import PyPDF2
|
|
|
|
| 4 |
import os
|
| 5 |
|
|
|
|
| 6 |
client = anthropic.Anthropic(api_key=os.environ.get("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"))
|
| 7 |
|
|
|
|
| 8 |
book_storage = {}
|
| 9 |
|
| 10 |
def extract_pdf_text(pdf_file):
|
|
|
|
| 11 |
if pdf_file is None:
|
| 12 |
return None, "No file uploaded"
|
|
|
|
| 13 |
try:
|
| 14 |
reader = PyPDF2.PdfReader(pdf_file)
|
| 15 |
pages = []
|
| 16 |
for i, page in enumerate(reader.pages):
|
| 17 |
text = page.extract_text()
|
| 18 |
+
if text and text.strip():
|
| 19 |
pages.append(f"[PAGE {i+1}]\n{text}")
|
|
|
|
| 20 |
full_text = "\n\n".join(pages)
|
| 21 |
return full_text, f"β
{len(reader.pages)} pages extracted successfully!"
|
| 22 |
except Exception as e:
|
| 23 |
return None, f"β Error: {str(e)}"
|
| 24 |
|
|
|
|
| 25 |
def upload_book(book_name, pdf_file):
|
|
|
|
| 26 |
if pdf_file is None:
|
| 27 |
return "Please select a PDF file."
|
|
|
|
| 28 |
text, msg = extract_pdf_text(pdf_file)
|
| 29 |
if text:
|
| 30 |
+
book_storage[book_name] = {"text": text, "pages": text.count("[PAGE ")}
|
|
|
|
|
|
|
|
|
|
| 31 |
return f"β
'{book_name}' uploaded! {msg}"
|
| 32 |
return msg
|
| 33 |
|
|
|
|
| 34 |
def ask_question(book_name, question, chat_history):
|
|
|
|
| 35 |
if not question.strip():
|
| 36 |
return chat_history, ""
|
| 37 |
+
|
| 38 |
if book_name not in book_storage:
|
| 39 |
+
chat_history.append({"role": "user", "content": question})
|
| 40 |
+
chat_history.append({"role": "assistant", "content": f"β οΈ Please upload '{book_name}' PDF first from the Admin Upload tab."})
|
| 41 |
return chat_history, ""
|
| 42 |
+
|
| 43 |
book_text = book_storage[book_name]["text"]
|
| 44 |
+
|
| 45 |
system_prompt = f"""You are a sacred scripture scholar for the AI Sacred Library.
|
| 46 |
|
| 47 |
You have the TEXT of: {book_name}
|
|
|
|
| 49 |
RULES:
|
| 50 |
1. Search the provided book text FIRST
|
| 51 |
2. Give EXACT original text from the book (in original language if present)
|
| 52 |
+
3. Always mention PAGE NUMBER using [PAGE X] markers in the text
|
| 53 |
4. Provide English translation
|
| 54 |
5. Provide Tafseer/Commentary/Summary
|
| 55 |
+
6. Format response clearly:
|
| 56 |
+
|
| 57 |
+
π ORIGINAL TEXT (Page X):
|
| 58 |
+
[exact text from book]
|
| 59 |
+
|
| 60 |
+
π TRANSLATION:
|
| 61 |
+
[English translation]
|
| 62 |
+
|
| 63 |
+
π TAFSEER / COMMENTARY:
|
| 64 |
+
[explanation and context]
|
| 65 |
+
|
| 66 |
+
π SOURCE: {book_name}, Page X
|
| 67 |
|
| 68 |
BOOK CONTENT:
|
| 69 |
{book_text[:60000]}"""
|
| 70 |
|
| 71 |
messages = []
|
| 72 |
+
for msg in chat_history[-10:]:
|
| 73 |
+
messages.append({"role": msg["role"], "content": msg["content"]})
|
|
|
|
| 74 |
messages.append({"role": "user", "content": question})
|
| 75 |
|
| 76 |
response = client.messages.create(
|
| 77 |
+
model="claude-sonnet-4-20250514",
|
| 78 |
max_tokens=1500,
|
| 79 |
system=system_prompt,
|
| 80 |
messages=messages
|
| 81 |
)
|
| 82 |
+
|
| 83 |
answer = response.content[0].text
|
| 84 |
+
chat_history.append({"role": "user", "content": question})
|
| 85 |
+
chat_history.append({"role": "assistant", "content": answer})
|
| 86 |
return chat_history, ""
|
| 87 |
|
|
|
|
|
|
|
| 88 |
BOOKS = [
|
| 89 |
"Al-Quran", "Bhagavad Gita", "Holy Bible", "Torah",
|
| 90 |
"Tripitaka (Buddhism)", "The Vedas", "Guru Granth Sahib", "Avesta"
|
| 91 |
]
|
| 92 |
|
| 93 |
+
css = """
|
| 94 |
+
.gradio-container { max-width: 900px !important; margin: auto !important; }
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
with gr.Blocks(title="Sacred Library β AI Scripture Database") as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
gr.Markdown("""
|
| 100 |
# π Sacred Library
|
|
|
|
| 104 |
""")
|
| 105 |
|
| 106 |
with gr.Tabs():
|
| 107 |
+
|
|
|
|
| 108 |
with gr.Tab("π¬ Chat with Scripture"):
|
| 109 |
+
book_select = gr.Dropdown(
|
| 110 |
+
choices=BOOKS,
|
| 111 |
+
value="Al-Quran",
|
| 112 |
+
label="π Select Scripture"
|
| 113 |
+
)
|
| 114 |
+
|
|
|
|
|
|
|
| 115 |
chatbot = gr.Chatbot(
|
| 116 |
label="Sacred Library AI",
|
| 117 |
height=450,
|
| 118 |
+
type="messages"
|
| 119 |
)
|
| 120 |
+
|
| 121 |
with gr.Row():
|
| 122 |
question_input = gr.Textbox(
|
| 123 |
+
placeholder='e.g. "page 1", "what is karma", "purpose of life", "Surah Al-Fatiha"',
|
| 124 |
label="Your Question",
|
| 125 |
scale=4
|
| 126 |
)
|
| 127 |
ask_btn = gr.Button("Ask β", variant="primary", scale=1)
|
| 128 |
+
|
| 129 |
gr.Examples(
|
| 130 |
examples=[
|
| 131 |
["Al-Quran", "Show me page 1"],
|
| 132 |
["Al-Quran", "What does Quran say about purpose of life?"],
|
| 133 |
["Bhagavad Gita", "What is karma according to Gita?"],
|
| 134 |
["Holy Bible", "Genesis chapter 1 verse 1"],
|
|
|
|
| 135 |
],
|
| 136 |
inputs=[book_select, question_input]
|
| 137 |
)
|
| 138 |
+
|
| 139 |
ask_btn.click(
|
| 140 |
ask_question,
|
| 141 |
inputs=[book_select, question_input, chatbot],
|
|
|
|
| 147 |
outputs=[chatbot, question_input]
|
| 148 |
)
|
| 149 |
|
|
|
|
| 150 |
with gr.Tab("π Admin β Upload Books"):
|
| 151 |
gr.Markdown("""
|
| 152 |
### Admin Book Upload Panel
|
| 153 |
Upload authentic scripture PDFs here. Users will get exact quotes from your uploaded books.
|
| 154 |
+
> Keep this Space **Private** on Hugging Face to restrict admin access.
|
|
|
|
|
|
|
| 155 |
""")
|
| 156 |
+
|
| 157 |
with gr.Row():
|
| 158 |
upload_book_name = gr.Dropdown(
|
| 159 |
choices=BOOKS,
|
| 160 |
value="Al-Quran",
|
| 161 |
+
label="Select Book",
|
| 162 |
scale=1
|
| 163 |
)
|
| 164 |
upload_pdf = gr.File(
|
|
|
|
| 166 |
file_types=[".pdf"],
|
| 167 |
scale=2
|
| 168 |
)
|
| 169 |
+
|
| 170 |
upload_btn = gr.Button("π€ Upload & Index Book", variant="primary")
|
| 171 |
+
upload_status = gr.Textbox(label="Status", interactive=False)
|
| 172 |
+
|
| 173 |
upload_btn.click(
|
| 174 |
upload_book,
|
| 175 |
inputs=[upload_book_name, upload_pdf],
|
| 176 |
outputs=[upload_status]
|
| 177 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
gr.Markdown("---\n*Sacred Library β Built with Claude AI + Gradio + PyPDF2*")
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
demo.launch()
|