File size: 1,347 Bytes
f7db77c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135abbc
 
f7db77c
135abbc
 
 
f7db77c
 
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
import gradio as gr
from commons.Model import model
from commons.Configs import configs
from commons.OpenAIClient import openaiClient
from prepareutils.Dataset import dataset
import numpy as np
import openai

# load the model once
clf = model.load()
# load dataset
qaDataset = dataset.loadDataset()


def predict(question, openaiKey):
    # set openaiKey
    configs.OPENAI_KEY = openaiKey
    openai.api_key = openaiKey
    # embed question
    questionEmbedding = openaiClient.generateEmbeddings([question])[0]
    # predict answer index
    answerIndex = clf.predict([questionEmbedding]).item()
    # get answer
    bestAnswer = qaDataset[answerIndex]
    return bestAnswer["answer"]


def randomExamples(numberOfExamples=15):
    # create random indexes in the range between 0 and len(qaDataset)
    randomIndexes = np.random.randint(0, len(qaDataset), numberOfExamples)
    examples = []
    for index in randomIndexes:
        question = qaDataset[index]["question"]
        examples.append([question])
    return examples


gr.Interface.load(
    "models/giovannefeitosa/chatbot-about-pele",
    fn=predict,
    inputs=[gr.Textbox(label="Question", lines=2),
            gr.Textbox(label="OpenAI Key")],
    outputs=gr.Textbox(label="Answer", lines=2),
    examples=randomExamples(),
).launch()