laitkor commited on
Commit
f949b05
·
verified ·
1 Parent(s): e8c77ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -68
app.py CHANGED
@@ -6,48 +6,48 @@ def greet(name):
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
 
@@ -59,14 +59,11 @@ def generate_questions(text):
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
 
@@ -77,56 +74,19 @@ def generate_answer(question, context):
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
 
6
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
  demo.launch()
8
  '''
9
+ import os
10
  from datasets import load_dataset
11
+ from transformers import AutoTokenizer, AutoModel, T5ForConditionalGeneration, T5Tokenizer, GPT2LMHeadModel, GPT2Tokenizer
 
 
12
  import faiss
13
  import numpy as np
14
+ import pytesseract
15
+ from PIL import Image
16
+ import gradio as gr
17
 
18
  # Define the path to the docs folder
19
  docs_path = "docs"
20
 
21
+ # Load images from the folder and extract text using pytesseract
22
  def load_documents(docs_path):
23
+ documents = []
24
+ for filename in os.listdir(docs_path):
25
+ if filename.endswith((".png", ".jpg", ".jpeg")):
26
+ image_path = os.path.join(docs_path, filename)
27
+ text = pytesseract.image_to_string(Image.open(image_path))
28
+ documents.append(text)
29
+ return documents
30
 
31
+ documents = load_documents(docs_path)
32
 
33
+ # Load model and tokenizer for encoding documents
 
 
34
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
35
  model = AutoModel.from_pretrained("distilbert-base-uncased")
36
 
37
  # Preprocess and encode documents
38
  def encode_documents(documents):
39
+ inputs = tokenizer(documents, return_tensors='pt', padding=True, truncation=True)
40
  outputs = model(**inputs)
41
  embeddings = outputs.last_hidden_state.mean(dim=1).detach().numpy()
42
  return embeddings
43
 
44
+ embeddings = encode_documents(documents)
45
 
46
+ # Index embeddings using FAISS
47
  index = faiss.IndexFlatL2(embeddings.shape[1])
48
  index.add(embeddings)
49
 
50
+ # Load T5 model and tokenizer for question generation
 
51
  t5_tokenizer = T5Tokenizer.from_pretrained("t5-small")
52
  t5_model = T5ForConditionalGeneration.from_pretrained("t5-small")
53
 
 
59
  return question
60
 
61
  def retrieve_documents(query, index, documents):
62
+ query_embedding = encode_documents([query])
63
  D, I = index.search(query_embedding, k=5)
64
  return [documents[i] for i in I[0]]
65
 
66
+ # Load GPT-2 model and tokenizer for answer generation
 
 
 
67
  gpt2_tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
68
  gpt2_model = GPT2LMHeadModel.from_pretrained("gpt2")
69
 
 
74
  answer = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
75
  return answer
76
 
77
+ # Fine-tuning the language model (example code provided earlier)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ # Generate documents based on prompts
80
  def generate_document(prompt):
81
+ input_ids = gpt2_tokenizer.encode(prompt, return_tensors="pt")
82
+ outputs = gpt2_model.generate(input_ids, max_length=512, num_return_sequences=1)
83
+ document = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
84
  return document
85
 
86
+ # Gradio Interface
 
 
87
  def rag_pipeline(query):
88
  question = generate_questions(query)
89
+ retrieved_docs = retrieve_documents(question, index, documents)
90
  context = " ".join(retrieved_docs)
91
  answer = generate_answer(question, context)
92
  return question, context, answer