CVchat / app.py
Aitor's picture
Formatting code
f4cb80a
raw
history blame
2.47 kB
import gradio as gr
import logging
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
from langchain.document_loaders import PDFMinerLoader
from langchain.indexes import VectorstoreIndexCreator
import os
def set_openai_key(raw_key):
logging.warning(raw_key)
os.environ["OPENAI_API_KEY"] = raw_key
def create_langchain(pdf_object):
logging.info(f"Creating langchain for {pdf_object.name}")
loader = PDFMinerLoader(pdf_object.name)
index_creator = VectorstoreIndexCreator()
docsearch = index_creator.from_loaders([loader])
chain = RetrievalQA.from_chain_type(
llm=OpenAI(),
chain_type="stuff",
retriever=docsearch.vectorstore.as_retriever(),
input_key="question",
verbose=True,
return_source_documents=True,
)
return chain, gr.Button.update(interactive=True)
def ask_question(chain, question_text):
logging.info(type(chain))
return chain({"question": question_text})["result"]
def create_ask(pdf_object, question_text):
loader = PDFMinerLoader(pdf_object.name)
index_creator = VectorstoreIndexCreator()
docsearch = index_creator.from_loaders([loader])
chain = RetrievalQA.from_chain_type(
llm=OpenAI(),
chain_type="stuff",
retriever=docsearch.vectorstore.as_retriever(),
input_key="question",
verbose=True,
return_source_documents=True,
)
return chain({"question": question_text})["result"]
with gr.Blocks() as demo:
# pdf_button = gr.Button(value="pdf_button")
oai_token = gr.Textbox(
label="OpenAI Token",
placeholder="Lm-iIas452gaw3erGtPar26gERGSA5RVkFJQST23WEG524EWEl",
)
oai_token.change(set_openai_key, oai_token)
pdf_object = gr.File(
label="Upload your CV in PDF format", file_count="single", type="file"
)
chain_state = gr.State()
question_placeholder = """
Enumerate the candidate's top 5 hard skills and rate them by importance from 0 to 5.
Example:
- Algebra 5/5
"""
question_box = gr.Textbox(label="Question", value=question_placeholder)
qa_button = gr.Button(value="Submit question", interactive=False)
lchain = pdf_object.change(
create_langchain, inputs=pdf_object, outputs=[chain_state, qa_button]
)
qa_button.click(
ask_question,
inputs=[chain_state, question_box],
outputs=gr.Textbox(label="Answer"),
)
demo.launch(debug=True)