File size: 2,271 Bytes
c68dfb5
 
e80297a
c68dfb5
e80297a
 
 
c68dfb5
e80297a
f4cb80a
e80297a
c68dfb5
 
 
 
 
 
e80297a
c68dfb5
6123c8c
e80297a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6123c8c
f4cb80a
 
 
 
6123c8c
e80297a
6123c8c
 
 
 
f4cb80a
6123c8c
f4cb80a
 
 
 
 
 
e80297a
 
6123c8c
 
 
 
 
f4cb80a
 
 
 
 
 
 
 
bf6416a
f4cb80a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import os

import gradio as gr
import requests
from langchain.chains import RetrievalQA
from langchain.document_loaders import PDFMinerLoader
from langchain.indexes import VectorstoreIndexCreator
from langchain.llms import OpenAI


def set_openai_key(raw_key):
    # Check if the API is valid
    headers = {"Authorization": f"Bearer {raw_key}"}
    response = requests.get("https://api.openai.com/v1/engines", headers=headers)
    if response.status_code != 200:
        raise gr.Error("API key is not valid. Check the key and try again.")
    
    os.environ["OPENAI_API_KEY"] = raw_key
    
    return gr.File.update(interactive=True)


def create_langchain(pdf_object):
    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):
    return chain({"question": question_text})["result"]


with gr.Blocks() as demo:
    # Layout
    oai_token = gr.Textbox(
        label="OpenAI Token",
        placeholder="Lm-iIas452gaw3erGtPar26gERGSA5RVkFJQST23WEG524EWEl",
    )

    pdf_object = gr.File(
        label="Upload your CV in PDF format",
        file_count="single",
        type="file",
        interactive=False,
    )

    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)

    # Sate objects
    chain_state = gr.State()

    # Actions
    oai_token.change(set_openai_key, inputs=oai_token, outputs=pdf_object)
    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)