Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 3 |
from langchain.text_splitter import CharacterTextSplitter
|
| 4 |
from langchain.vectorstores import Chroma
|
|
@@ -8,7 +9,6 @@ from langchain.document_loaders import PyPDFLoader
|
|
| 8 |
import os
|
| 9 |
import fitz
|
| 10 |
from PIL import Image
|
| 11 |
-
import streamlit as st
|
| 12 |
|
| 13 |
# Global variables
|
| 14 |
COUNT, N = 0, 0
|
|
@@ -18,11 +18,11 @@ chain = None # Initialize chain as None
|
|
| 18 |
# Function to set the OpenAI API key
|
| 19 |
def set_apikey(api_key):
|
| 20 |
os.environ['OPENAI_API_KEY'] = api_key
|
| 21 |
-
return disable_box
|
| 22 |
|
| 23 |
# Function to enable the API key input box
|
| 24 |
def enable_api_box():
|
| 25 |
-
return enable_box
|
| 26 |
|
| 27 |
# Function to add text to the chat history
|
| 28 |
def add_text(history, text):
|
|
@@ -33,36 +33,39 @@ def add_text(history, text):
|
|
| 33 |
|
| 34 |
# Function to process the PDF file and create a conversation chain
|
| 35 |
def process_file(file):
|
| 36 |
-
global chain
|
| 37 |
if 'OPENAI_API_KEY' not in os.environ:
|
| 38 |
raise gr.Error('Upload your OpenAI API key')
|
| 39 |
|
|
|
|
| 40 |
loader = PyPDFLoader(file.name)
|
| 41 |
documents = loader.load()
|
| 42 |
embeddings = OpenAIEmbeddings()
|
| 43 |
pdfsearch = Chroma.from_documents(documents, embeddings)
|
|
|
|
| 44 |
chain = ConversationalRetrievalChain.from_llm(ChatOpenAI(temperature=0.3),
|
| 45 |
retriever=pdfsearch.as_retriever(search_kwargs={"k": 1}),
|
| 46 |
return_source_documents=True)
|
| 47 |
return chain
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
def generate_response(history, query,
|
| 51 |
-
global COUNT, N, chat_history, chain
|
| 52 |
-
if not
|
| 53 |
raise gr.Error(message='Upload a PDF')
|
| 54 |
|
| 55 |
if COUNT == 0:
|
| 56 |
-
chain = process_file(
|
| 57 |
COUNT += 1
|
| 58 |
|
| 59 |
-
|
|
|
|
| 60 |
chat_history += [(query, result["answer"])]
|
| 61 |
-
N = list(result['source_documents'][0])[1][1]['page']
|
| 62 |
|
| 63 |
for char in result['answer']:
|
| 64 |
-
history[-1][-1] += char
|
| 65 |
-
|
| 66 |
|
| 67 |
# Function to render a specific page of a PDF file as an image
|
| 68 |
def render_file(file):
|
|
@@ -73,117 +76,48 @@ def render_file(file):
|
|
| 73 |
image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples)
|
| 74 |
return image
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
# with gr.Blocks() as demo:
|
| 78 |
-
# with gr.Column():
|
| 79 |
-
# gr.Markdown("""
|
| 80 |
-
# <style>
|
| 81 |
-
# .image-container { height: 680px; }
|
| 82 |
-
# </style>
|
| 83 |
-
# """)
|
| 84 |
-
# with gr.Row():
|
| 85 |
-
# enable_box = gr.Textbox(placeholder='Enter OpenAI API key',
|
| 86 |
-
# show_label=False, interactive=True)
|
| 87 |
-
# disable_box = gr.Textbox(value='OpenAI API key is Set', interactive=False)
|
| 88 |
-
# change_api_key = gr.Button('Change Key')
|
| 89 |
-
# with gr.Row():
|
| 90 |
-
# chatbot = gr.Chatbot(value=[], elem_id='chatbot')
|
| 91 |
-
# show_img = gr.Image(label='Upload PDF')
|
| 92 |
-
|
| 93 |
-
# # Set up event handlers
|
| 94 |
-
|
| 95 |
-
# # Event handler for submitting the OpenAI API key
|
| 96 |
-
# enable_box.submit(fn=set_apikey, inputs=[enable_box], outputs=[disable_box])
|
| 97 |
-
|
| 98 |
-
# # Event handler for changing the API key
|
| 99 |
-
# change_api_key.click(fn=enable_api_box, outputs=[enable_box])
|
| 100 |
-
|
| 101 |
-
|
| 102 |
def render_first(pdf_file):
|
| 103 |
-
#
|
| 104 |
-
|
| 105 |
-
return image
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
with gr.Blocks() as demo:
|
| 109 |
-
with gr.Column():
|
| 110 |
-
gr.Markdown("""
|
| 111 |
-
<style>
|
| 112 |
-
.image-container { height: 680px; }
|
| 113 |
-
</style>
|
| 114 |
-
""")
|
| 115 |
-
with gr.Row():
|
| 116 |
-
enable_box = gr.Textbox(placeholder='Enter OpenAI API key',
|
| 117 |
-
show_label=False, interactive=True)
|
| 118 |
-
disable_box = gr.Textbox(value='OpenAI API key is Set', interactive=False)
|
| 119 |
-
change_api_key = gr.Button('Change Key')
|
| 120 |
-
with gr.Row():
|
| 121 |
-
chatbot = gr.Chatbot(value=[], elem_id='chatbot')
|
| 122 |
-
show_img = gr.Image(label='Upload PDF')
|
| 123 |
-
pdf_upload = gr.UploadButton("📁 Upload a PDF", file_types=[".pdf"]) # Added
|
| 124 |
-
|
| 125 |
-
# Event handlers
|
| 126 |
-
enable_box.submit(fn=set_apikey, inputs=[enable_box], outputs=[disable_box])
|
| 127 |
-
change_api_key.click(fn=enable_api_box, outputs=[enable_box])
|
| 128 |
-
pdf_upload.upload(fn=render_first, inputs=[pdf_upload], outputs=[show_img]) # Corrected
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
txt = gr.Textbox(label="Enter your query", placeholder="Ask a question...") # Add Textbox
|
| 132 |
-
submit_btn = gr.Button('Submit') # Added the Submit button
|
| 133 |
-
submit_btn.click(
|
| 134 |
-
fn=add_text,
|
| 135 |
-
inputs=[chatbot, txt], # Assuming 'txt' is your textbox for query input
|
| 136 |
-
outputs=[chatbot],
|
| 137 |
-
queue=False
|
| 138 |
-
).success(
|
| 139 |
-
fn=generate_response,
|
| 140 |
-
inputs=[chatbot, txt, pdf_upload], # Changed from 'btn'
|
| 141 |
-
outputs=[chatbot, txt]
|
| 142 |
-
).success(
|
| 143 |
-
fn=render_file,
|
| 144 |
-
inputs=[pdf_upload], # Changed from 'btn'
|
| 145 |
-
outputs=[show_img]
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
-
# demo.launch(server_port=7861)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
def add_text(history, text):
|
| 152 |
-
if not text:
|
| 153 |
-
raise gr.Error('Enter text')
|
| 154 |
-
history = history + [(text, '')]
|
| 155 |
-
return history
|
| 156 |
-
|
| 157 |
-
def render_first(pdf_file):
|
| 158 |
-
# ... Logic to process the PDF (extract text, create summary, etc.)
|
| 159 |
-
# ... Generate a simple image as a placeholder
|
| 160 |
-
image = Image.new('RGB', (600, 400), color = 'white') # Example
|
| 161 |
-
|
| 162 |
return image
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
with st.container():
|
| 168 |
-
gr.Markdown("""
|
| 169 |
-
<style>
|
| 170 |
-
|
| 171 |
-
</style>
|
| 172 |
-
""")
|
| 173 |
-
with gr.Row():
|
| 174 |
-
enable_box = gr.Textbox(placeholder='Enter OpenAI API key',
|
| 175 |
-
show_label=False, interactive=True)
|
| 176 |
-
disable_box = gr.Textbox(value='OpenAI API key is Set', interactive=False)
|
| 177 |
-
change_api_key = gr.Button('Change Key')
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
pdf_upload = gr.UploadButton("📁 Upload a PDF", file_types=[".pdf"])
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
# If you only want a Gradio interface, launch Gradio
|
| 187 |
if __name__ == "__main__":
|
| 188 |
gr.Interface(
|
| 189 |
[render_first, add_text, generate_response, render_file],
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import streamlit as st
|
| 3 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 4 |
from langchain.text_splitter import CharacterTextSplitter
|
| 5 |
from langchain.vectorstores import Chroma
|
|
|
|
| 9 |
import os
|
| 10 |
import fitz
|
| 11 |
from PIL import Image
|
|
|
|
| 12 |
|
| 13 |
# Global variables
|
| 14 |
COUNT, N = 0, 0
|
|
|
|
| 18 |
# Function to set the OpenAI API key
|
| 19 |
def set_apikey(api_key):
|
| 20 |
os.environ['OPENAI_API_KEY'] = api_key
|
| 21 |
+
return disable_box
|
| 22 |
|
| 23 |
# Function to enable the API key input box
|
| 24 |
def enable_api_box():
|
| 25 |
+
return enable_box
|
| 26 |
|
| 27 |
# Function to add text to the chat history
|
| 28 |
def add_text(history, text):
|
|
|
|
| 33 |
|
| 34 |
# Function to process the PDF file and create a conversation chain
|
| 35 |
def process_file(file):
|
| 36 |
+
global chain
|
| 37 |
if 'OPENAI_API_KEY' not in os.environ:
|
| 38 |
raise gr.Error('Upload your OpenAI API key')
|
| 39 |
|
| 40 |
+
# Replace with your actual PDF processing logic
|
| 41 |
loader = PyPDFLoader(file.name)
|
| 42 |
documents = loader.load()
|
| 43 |
embeddings = OpenAIEmbeddings()
|
| 44 |
pdfsearch = Chroma.from_documents(documents, embeddings)
|
| 45 |
+
|
| 46 |
chain = ConversationalRetrievalChain.from_llm(ChatOpenAI(temperature=0.3),
|
| 47 |
retriever=pdfsearch.as_retriever(search_kwargs={"k": 1}),
|
| 48 |
return_source_documents=True)
|
| 49 |
return chain
|
| 50 |
|
| 51 |
+
# Function to generate a response based on the chat history and query
|
| 52 |
+
def generate_response(history, query, pdf_upload):
|
| 53 |
+
global COUNT, N, chat_history, chain
|
| 54 |
+
if not pdf_upload:
|
| 55 |
raise gr.Error(message='Upload a PDF')
|
| 56 |
|
| 57 |
if COUNT == 0:
|
| 58 |
+
chain = process_file(pdf_upload)
|
| 59 |
COUNT += 1
|
| 60 |
|
| 61 |
+
# Replace with your LangChain logic to generate a response
|
| 62 |
+
result = chain({"question": query, 'chat_history': chat_history}, return_only_outputs=True)
|
| 63 |
chat_history += [(query, result["answer"])]
|
| 64 |
+
N = list(result['source_documents'][0])[1][1]['page'] # Adjust as needed
|
| 65 |
|
| 66 |
for char in result['answer']:
|
| 67 |
+
history[-1][-1] += char
|
| 68 |
+
return history, ''
|
| 69 |
|
| 70 |
# Function to render a specific page of a PDF file as an image
|
| 71 |
def render_file(file):
|
|
|
|
| 76 |
image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples)
|
| 77 |
return image
|
| 78 |
|
| 79 |
+
# Function to render initial content from the PDF
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
def render_first(pdf_file):
|
| 81 |
+
# Replace with logic to process the PDF and generate an initial image
|
| 82 |
+
image = Image.new('RGB', (600, 400), color = 'white') # Placeholder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return image
|
| 84 |
|
| 85 |
+
# Streamlit & Gradio Interface
|
| 86 |
+
st.title("PDF-Powered Chatbot")
|
| 87 |
+
|
| 88 |
+
with st.container():
|
| 89 |
+
gr.Markdown("""
|
| 90 |
+
<style>
|
| 91 |
+
.image-container { height: 680px; }
|
| 92 |
+
</style>
|
| 93 |
+
""")
|
| 94 |
+
with gr.Row():
|
| 95 |
+
enable_box = gr.Textbox(placeholder='Enter OpenAI API key',
|
| 96 |
+
show_label=False, interactive=True)
|
| 97 |
+
disable_box = gr.Textbox(value='OpenAI API key is Set', interactive=False)
|
| 98 |
+
change_api_key = gr.Button('Change Key')
|
| 99 |
+
|
| 100 |
+
with gr.Row():
|
| 101 |
+
chatbot = gr.Chatbot(value=[], elem_id='chatbot')
|
| 102 |
+
show_img = gr.Image(label='Upload PDF')
|
| 103 |
pdf_upload = gr.UploadButton("📁 Upload a PDF", file_types=[".pdf"])
|
| 104 |
|
| 105 |
+
# Event handlers
|
| 106 |
+
enable_box.submit(fn=set_apikey, inputs=[enable_box], outputs=[disable_box])
|
| 107 |
+
change_api_key.click(fn=enable_api_box, outputs=[enable_box])
|
| 108 |
+
pdf_upload.upload(fn=render_first, inputs=[pdf_upload], outputs=[show_img])
|
| 109 |
+
|
| 110 |
+
txt = gr.Textbox(label="Enter your query", placeholder="Ask a question...")
|
| 111 |
+
submit_btn = gr.Button('Submit')
|
| 112 |
+
|
| 113 |
+
submit_btn.click(
|
| 114 |
+
fn=add_text, inputs=[chatbot, txt], outputs=[chatbot], queue=False
|
| 115 |
+
).success(
|
| 116 |
+
fn=generate_response, inputs=[chatbot, txt, pdf_upload], outputs=[chatbot, txt]
|
| 117 |
+
).success(
|
| 118 |
+
fn=render_file, inputs=[pdf_upload], outputs=[show_img]
|
| 119 |
+
)
|
| 120 |
|
|
|
|
| 121 |
if __name__ == "__main__":
|
| 122 |
gr.Interface(
|
| 123 |
[render_first, add_text, generate_response, render_file],
|