gaur3009 commited on
Commit
b2c8039
·
verified ·
1 Parent(s): cb10fd6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import BertTokenizer, BertModel, GPT2LMHeadModel, GPT2Tokenizer
3
+ import numpy as np
4
+ import pandas as pd
5
+ import os
6
+ import gradio as gr
7
+
8
+ # Load the models and tokenizers
9
+ bert_model_name = 'bert-base-uncased'
10
+ bert_tokenizer = BertTokenizer.from_pretrained(bert_model_name)
11
+ bert_model = BertModel.from_pretrained(bert_model_name)
12
+
13
+ gpt2_model_name = 'gpt2'
14
+ gpt2_tokenizer = GPT2Tokenizer.from_pretrained(gpt2_model_name)
15
+ gpt2_model = GPT2LMHeadModel.from_pretrained(gpt2_model_name)
16
+
17
+ # Load the data
18
+ data = {
19
+ "questions": [
20
+ "What is Rookus?",
21
+ "How does Rookus use AI in its designs?",
22
+ "What products does Rookus offer?",
23
+ "Can I see samples of Rookus' designs?",
24
+ "How can I join the waitlist for Rookus?",
25
+ "How does Rookus ensure the quality of its AI-generated designs?",
26
+ "Is there a custom design option available at Rookus?",
27
+ "How long does it take to receive a product from Rookus?"
28
+ ],
29
+ "answers": [
30
+ "Rookus is a startup that leverages AI to create unique designs for various products such as clothes, posters, and different arts and crafts.",
31
+ "Rookus uses advanced AI algorithms to generate innovative and aesthetically pleasing designs. These AI models are trained on vast datasets of art and design to produce high-quality mockups.",
32
+ "Rookus offers a variety of products, including clothing, posters, and a range of arts and crafts items, all featuring AI-generated designs.",
33
+ "Yes, Rookus provides samples of its designs on its website. You can view a gallery of products showcasing the AI-generated artwork.",
34
+ "To join the waitlist for Rookus, visit our website and sign up with your email. You'll receive updates on our launch and exclusive early access opportunities.",
35
+ "Rookus ensures the quality of its AI-generated designs through rigorous testing and refinement. Each design goes through multiple review stages to ensure it meets our high standards.",
36
+ "Yes, Rookus offers custom design options. You can submit your preferences, and our AI will generate a design tailored to your specifications.",
37
+ "The delivery time for products from Rookus varies based on the product type and location. Typically, it takes 2-4 weeks for production and delivery."
38
+ ],
39
+ "default_answers": "I'm sorry, I cannot answer this right now. Your question has been saved, and we will get back to you with a response soon."
40
+ }
41
+
42
+ def get_bert_embeddings(texts):
43
+ inputs = bert_tokenizer(texts, return_tensors='pt', padding=True, truncation=True)
44
+ with torch.no_grad():
45
+ outputs = bert_model(**inputs)
46
+ return outputs.last_hidden_state[:, 0, :].numpy()
47
+
48
+ def get_closest_question(user_query, questions, threshold=0.95):
49
+ all_texts = questions + [user_query]
50
+ embeddings = get_bert_embeddings(all_texts)
51
+ cosine_similarities = np.dot(embeddings[-1], embeddings[:-1].T) / (
52
+ np.linalg.norm(embeddings[-1]) * np.linalg.norm(embeddings[:-1], axis=1)
53
+ )
54
+ max_similarity = np.max(cosine_similarities)
55
+
56
+ if max_similarity >= threshold:
57
+ most_similar_index = np.argmax(cosine_similarities)
58
+ return questions[most_similar_index], max_similarity
59
+ else:
60
+ return None, max_similarity
61
+
62
+ def generate_gpt2_response(prompt, model, tokenizer, max_length=100):
63
+ inputs = tokenizer.encode(prompt, return_tensors='pt')
64
+ outputs = model.generate(inputs, max_length=max_length, num_return_sequences=1)
65
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
66
+
67
+ def answer_query(user_query):
68
+ closest_question, similarity = get_closest_question(user_query, data['questions'], threshold=0.95)
69
+ if closest_question and similarity >= 0.95:
70
+ answer_index = data['questions'].index(closest_question)
71
+ answer = data['answers'][answer_index]
72
+ else:
73
+ excel_file = 'new_questions1.xlsx'
74
+ if not os.path.isfile(excel_file):
75
+ df = pd.DataFrame(columns=['question'])
76
+ df.to_excel(excel_file, index=False)
77
+
78
+ new_data = pd.DataFrame({'questions': [user_query]})
79
+ df = pd.read_excel(excel_file)
80
+ df = pd.concat([df, new_data], ignore_index=True)
81
+ with pd.ExcelWriter(excel_file, engine='openpyxl', mode='w') as writer:
82
+ df.to_excel(writer, index=False)
83
+ answer = data['default_answers']
84
+
85
+ return answer
86
+
87
+ iface = gr.Interface(
88
+ fn=answer_query,
89
+ inputs="text",
90
+ outputs="text",
91
+ title="Rookus AI Query Interface",
92
+ description="Ask questions about Rookus and get answers generated by AI."
93
+ )
94
+
95
+ if __name__ == "__main__":
96
+ iface.launch()