laitkor commited on
Commit
51ffca9
·
verified ·
1 Parent(s): 15ccde6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -2
app.py CHANGED
@@ -1,7 +1,145 @@
1
- import gradio as gr
2
 
3
  def greet(name):
4
  return "Hello " + name + "!!"
5
 
6
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*import gradio as gr
2
 
3
  def greet(name):
4
  return "Hello " + name + "!!"
5
 
6
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
+ demo.launch()*/
8
+
9
+ from datasets import load_dataset
10
+ from transformers import AutoTokenizer, AutoModel
11
+ from transformers import T5ForConditionalGeneration, T5Tokenizer
12
+
13
+ import faiss
14
+ import numpy as np
15
+ import os
16
+
17
+
18
+ # Define the path to the docs folder
19
+ docs_path = "docs"
20
+
21
+ # Load documents from the folder
22
+ def load_documents(docs_path):
23
+ data_files = {"train": [os.path.join(docs_path, file) for file in os.listdir(docs_path) if file.endswith(".txt")]}
24
+ dataset = load_dataset("text", data_files=data_files)
25
+ return dataset["train"]
26
+
27
+ documents_dataset = load_documents(docs_path)
28
+
29
+
30
+
31
+
32
+ # Load model and tokenizer
33
+ tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
34
+ model = AutoModel.from_pretrained("distilbert-base-uncased")
35
+
36
+ # Preprocess and encode documents
37
+ def encode_documents(documents):
38
+ inputs = tokenizer(documents["text"], return_tensors='pt', padding=True, truncation=True)
39
+ outputs = model(**inputs)
40
+ embeddings = outputs.last_hidden_state.mean(dim=1).detach().numpy()
41
+ return embeddings
42
+
43
+ embeddings = encode_documents(documents_dataset)
44
+
45
+ # Index embeddings
46
+ index = faiss.IndexFlatL2(embeddings.shape[1])
47
+ index.add(embeddings)
48
+
49
+
50
+ # Load T5 model and tokenizer
51
+ t5_tokenizer = T5Tokenizer.from_pretrained("t5-small")
52
+ t5_model = T5ForConditionalGeneration.from_pretrained("t5-small")
53
+
54
+ def generate_questions(text):
55
+ input_text = f"generate question: {text}"
56
+ input_ids = t5_tokenizer.encode(input_text, return_tensors="pt")
57
+ outputs = t5_model.generate(input_ids)
58
+ question = t5_tokenizer.decode(outputs[0], skip_special_tokens=True)
59
+ return question
60
+
61
+ def retrieve_documents(query, index, documents):
62
+ query_embedding = encode_documents({"text": [query]})
63
+ D, I = index.search(query_embedding, k=5)
64
+ return [documents[i] for i in I[0]]
65
+
66
+ # Answer Generation
67
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
68
+
69
+ # Load GPT-2 model and tokenizer
70
+ gpt2_tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
71
+ gpt2_model = GPT2LMHeadModel.from_pretrained("gpt2")
72
+
73
+ def generate_answer(question, context):
74
+ input_text = f"Question: {question}\nContext: {context}\nAnswer:"
75
+ input_ids = gpt2_tokenizer.encode(input_text, return_tensors="pt")
76
+ outputs = gpt2_model.generate(input_ids, max_length=150)
77
+ answer = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
78
+ return answer
79
+
80
+ #fine tuning the language model
81
+
82
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer, Trainer, TrainingArguments
83
+
84
+ # Load dataset
85
+ dataset = load_dataset("text", data_files={"train": "docs/*.txt"})
86
+
87
+ # Load model and tokenizer
88
+ model_name = "gpt2"
89
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
90
+ model = GPT2LMHeadModel.from_pretrained(model_name)
91
+
92
+ # Tokenize the dataset
93
+ def tokenize_function(examples):
94
+ return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=512)
95
+
96
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
97
+
98
+ # Set training arguments
99
+ training_args = TrainingArguments(
100
+ output_dir="./results",
101
+ evaluation_strategy="epoch",
102
+ learning_rate=2e-5,
103
+ per_device_train_batch_size=2,
104
+ num_train_epochs=3,
105
+ weight_decay=0.01,
106
+ )
107
+
108
+ # Initialize Trainer
109
+ trainer = Trainer(
110
+ model=model,
111
+ args=training_args,
112
+ train_dataset=tokenized_datasets["train"],
113
+ )
114
+
115
+ # Fine-tune the model
116
+ trainer.train()
117
+
118
+ def generate_document(prompt):
119
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
120
+ outputs = model.generate(input_ids, max_length=512, num_return_sequences=1)
121
+ document = tokenizer.decode(outputs[0], skip_special_tokens=True)
122
+ return document
123
+
124
+ # Gradio
125
+ import gradio as gr
126
+
127
+ def rag_pipeline(query):
128
+ question = generate_questions(query)
129
+ retrieved_docs = retrieve_documents(question, index, documents_dataset["text"])
130
+ context = " ".join(retrieved_docs)
131
+ answer = generate_answer(question, context)
132
+ return question, context, answer
133
+
134
+ def generate_support_document(prompt):
135
+ return generate_document(prompt)
136
+
137
+ iface = gr.Interface(
138
+ fn=[rag_pipeline, generate_support_document],
139
+ inputs=["text", "text"],
140
+ outputs=["text", "text", "text", "text"],
141
+ title="RAG Pipeline for Product Support",
142
+ description="Ask a question about product support and get a detailed answer. Generate new support documents based on prompts."
143
+ )
144
+
145
+ iface.launch()