File size: 2,449 Bytes
055a3f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136ff58
055a3f7
 
 
 
 
 
 
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
80
81
82
83
84
import os
import os.path
import pymongo
from pymongo.mongo_client import MongoClient
import gradio as gr
import certifi

MONGODB_ATLAS_DB_PASSWORD = os.environ['MONGODB_ATLAS_DB_PASSWORD']


from llama_index.vector_stores.mongodb import MongoDBAtlasVectorSearch

from llama_index import (
    VectorStoreIndex,
    SimpleDirectoryReader,
    StorageContext,
    load_index_from_storage,
)


mongo_uri = (
    f"mongodb+srv://arkiitkgp:{MONGODB_ATLAS_DB_PASSWORD}@genaicluster0.fgmvvsx.mongodb.net/?retryWrites=true&w=majority"
)
mongodb_client = pymongo.MongoClient(mongo_uri, tlsCAFile=certifi.where())

# Send a ping to confirm a successful connection
try:
    mongodb_client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)


store = MongoDBAtlasVectorSearch(mongodb_client, db_name='testdb1', collection_name='dummyIndex', index_name='vector_index')
# storage_context = StorageContext.from_defaults(vector_store=store)
# documents = SimpleDirectoryReader(
#         "temp", 
#         file_metadata=get_metadata_from_filename, 
#         required_exts=['.pdf', '.docx'],
#         recursive=True,
#     ).load_data()

# construct index
# index = VectorStoreIndex.from_documents(
#     documents, storage_context=storage_context
# )

index = VectorStoreIndex.from_vector_store(store)


def get_answer(query):
    response = index.as_query_engine(streaming=True).query(query)
    # response.print_response_stream()
    return response



###### GRADIO #################################

classes = ['Class 10', 'Class 9']
subjects = ['Science']

def get_streaming_answer(input_query):
    r = get_answer(input_query)
    ans = ""
    for new_tokens in r.response_gen:
        ans += new_tokens
        yield ans

with gr.Blocks() as demo:
    gr.Markdown("""# NCERT Tutor \n ### Type your question...""")
    with gr.Tab("For Students"):
        choose_class = gr.Dropdown(label= "Class", choices=classes)
        choose_subject = gr.Dropdown(label="Subject", choices=subjects)
        question_input = gr.Textbox(label="Enter question...")
        submit_button = gr.Button("Ask")
        response_output = gr.Textbox(label="Answer...", lines=5)
        
    with gr.Tab("For Teachers"):
        gr.Markdown("Coming soon...")

    submit_button.click(fn=get_streaming_answer, inputs=question_input, outputs=response_output)
  
demo.launch(share=True, debug=True)