CarolineDelva commited on
Commit
19855be
·
verified ·
1 Parent(s): caea9a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -114
app.py CHANGED
@@ -3,129 +3,148 @@ from huggingface_hub import InferenceClient
3
  import os
4
  import pandas as pd
5
  from sklearn.metrics.pairwise import cosine_similarity
6
- from InstructorEmbedding import INSTRUCTOR
 
 
 
 
7
 
8
- """
9
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
10
- """
11
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
12
 
 
 
 
 
 
 
 
 
13
 
 
14
 
15
- class InformationRetrieval():
16
-
17
- def __init__(self, datapath):
 
 
 
 
 
 
 
18
  self.text_data = []
19
- self.filepaths = []
20
- try:
21
- if os.path.isdir(datapath):
22
- for text in os.listdir(datapath):
23
- fullpath = os.path.join(datapath, text)
24
-
25
- if text.endswith('.txt'):
26
- with open(fullpath, 'r', encoding='utf-8') as file:
27
- content = file.read()
28
- self.text_data.append(content)
29
- self.filepaths.append(fullpath)
30
- else:
31
- raise TypeError("This is not a right directory.")
32
- except FileNotFoundError as e:
33
- print(f"File not found: {e}")
34
- except TypeError as e:
35
- print(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  except Exception as e:
37
- print(e)
38
-
39
- def model(self, whatineed=None):
40
- model = INSTRUCTOR('hkunlp/instructor-large')
41
-
42
- if whatineed is None:
43
- whatineed = input("Which document are you looking to retrieve: ")
44
-
45
  embeddings_dict = {}
46
-
47
- embeddings_a = model.encode([['The text I provide:', whatineed]])
48
-
49
  for i, text in enumerate(self.text_data):
50
- embeddings_b = model.encode([['The text I am searching through:', text]])
51
-
52
- similarities = cosine_similarity(embeddings_a, embeddings_b)
53
-
54
- embeddings_dict[self.filepaths[i]] = (embeddings_b, similarities)
55
- # print(f"Embeddings for '{self.filepaths[i]}': {embeddings_b}")
56
-
57
- sorted_embeddings = sorted(embeddings_dict.items(), key=lambda item: item[1][1][0][0], reverse=True)
58
-
59
- empty_dict = {}
60
- for path, (embedding, similarity) in sorted_embeddings:
61
- #print(f"File Path: {path}, Similarity: {similarity[0][0]}")
62
- empty_dict[path] =similarity[0][0]
63
- print(empty_dict)
64
- return empty_dict
65
-
66
-
67
- mytextir = InformationRetrieval('data')
68
- #mytextir.model()
69
-
70
-
71
-
72
- def respond(
73
- message,
74
- history: list[tuple[str, str]],
75
- system_message,
76
- max_tokens,
77
- temperature,
78
- top_p,
79
- ):
80
-
81
- ir_results = mytextir.model(message)
82
-
83
- messages = [{"role": "system", "content": system_message}]
84
-
85
- response = f"IR Results:\n{ir_results}\n\n"
86
-
87
- for val in history:
88
- if val[0]:
89
- messages.append({"role": "user", "content": val[0]})
90
- if val[1]:
91
- messages.append({"role": "assistant", "content": val[1]})
92
-
93
- messages.append({"role": "user", "content": message})
94
-
95
-
96
-
97
- for message in client.chat_completion(
98
- messages,
99
- max_tokens=max_tokens,
100
- stream=True,
101
- temperature=temperature,
102
- top_p=top_p,
103
- ):
104
- token = message.choices[0].delta.content
105
-
106
- response += token
107
- yield response
108
-
109
-
110
- """
111
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
112
- """
113
- demo = gr.ChatInterface(
114
- respond,
115
- additional_inputs=[
116
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
117
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
118
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
119
- gr.Slider(
120
- minimum=0.1,
121
- maximum=1.0,
122
- value=0.95,
123
- step=0.05,
124
- label="Top-p (nucleus sampling)",
125
- ),
126
  ],
 
127
  )
128
 
129
-
130
  if __name__ == "__main__":
131
- demo.launch()
 
3
  import os
4
  import pandas as pd
5
  from sklearn.metrics.pairwise import cosine_similarity
6
+ from sentence_transformers import SentenceTransformer
7
+ from dotenv import load_dotenv
8
+ from huggingface_hub import HfApi
9
+ import zipfile
10
+ import json
11
 
 
 
 
 
12
 
13
+ from sklearn.metrics.pairwise import cosine_similarity
14
+
15
+ load_dotenv()
16
+
17
+ API_KEY = os.getenv("api_key")
18
+
19
+ if API_KEY is None:
20
+ raise ValueError("API key not found. Make sure you have a valid .env file with the 'api_key' variable.")
21
 
22
+ os.environ["HUGGINGFACE_HUB_TOKEN"] = API_KEY
23
 
24
+ api = HfApi()
25
+
26
+ models = api.list_models()
27
+ print(models)
28
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=API_KEY)
29
+
30
+
31
+ class InformationRetrieval:
32
+ def __init__(self, filepaths):
33
+
34
  self.text_data = []
35
+ self.filepaths = filepaths
36
+ try:
37
+ for filepath in self.filepaths:
38
+
39
+ try:
40
+ with open(filepath, 'r', encoding='utf-8') as file:
41
+ content = file.read()
42
+ except UnicodeDecodeError:
43
+ with open(filepath, 'r', encoding='ISO-8859-1') as file:
44
+ content = file.read()
45
+ self.text_data.append(content)
46
+ print("Files loaded successfully.")
47
+ except Exception as e:
48
+ print(f"Error reading files: {e}")
49
+ self.text_data = []
50
+
51
+
52
+ try:
53
+ self.model = SentenceTransformer('all-MiniLM-L6-v2')
54
+ print("Sentence Transformer model loaded successfully.")
55
+ except Exception as e:
56
+ print(f"Error loading model: {e}")
57
+ self.model = None
58
+ def encode_and_retrieve(self, query):
59
+ if not query:
60
+ query = "default text"
61
+
62
+ if not self.model:
63
+ print("Model is not initialized.")
64
+ return {}
65
+
66
+ try:
67
+ query_embedding = self.model.encode([query])
68
+ query_embedding = query_embedding.reshape(1, -1)
69
  except Exception as e:
70
+ print(f"Error encoding query: {e}")
71
+ return {}
72
+
 
 
 
 
 
73
  embeddings_dict = {}
74
+
 
 
75
  for i, text in enumerate(self.text_data):
76
+ try:
77
+ truncated_text = text[:1000]
78
+
79
+ doc_embedding = self.model.encode([truncated_text])
80
+
81
+ if doc_embedding.ndim == 3:
82
+ doc_embedding = doc_embedding.reshape(doc_embedding.shape[0], -1)
83
+ elif doc_embedding.ndim == 1:
84
+ doc_embedding = doc_embedding.reshape(1, -1)
85
+
86
+ similarity = cosine_similarity(query_embedding, doc_embedding)[0][0]
87
+ embeddings_dict[self.filepaths[i]] = similarity
88
+ except Exception as e:
89
+ print(f"Error processing document {self.filepaths[i]}: {e}")
90
+
91
+ sorted_embeddings = sorted(embeddings_dict.items(), key=lambda item: item[1], reverse=True)
92
+
93
+ result_dict = {path: score for path, score in sorted_embeddings}
94
+ return result_dict
95
+
96
+
97
+
98
+ def process_zip_file(zip_file):
99
+ try:
100
+ zip_filepath = zip_file.name
101
+ filepaths = []
102
+ with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
103
+ zip_ref.extractall("extracted_files")
104
+ for filename in zip_ref.namelist():
105
+ if filename.startswith('__MACOSX/') or filename.startswith('._'):
106
+ continue
107
+ if filename.endswith('.txt'):
108
+ filepaths.append(os.path.join("extracted_files", filename))
109
+ return {"files": filepaths}
110
+ except Exception as e:
111
+ return {"error": f"Error processing zip file: {e}"}
112
+
113
+
114
+
115
+ def respond(zip_file, query):
116
+ if zip_file is None:
117
+ return {"error": "Please upload a .zip file containing the data."}
118
+
119
+ filepaths = process_zip_file(zip_file)
120
+ if "error" in filepaths:
121
+ return filepaths
122
+
123
+ extracted_files = filepaths["files"]
124
+ print(f"Extracted files: {extracted_files}")
125
+
126
+ ir_model = InformationRetrieval(extracted_files)
127
+
128
+ ir_results = ir_model.encode_and_retrieve(query)
129
+
130
+ if not ir_results:
131
+ return json.dumps({"error": "No results found for the given query."})
132
+
133
+ results = []
134
+ for filepath, score in ir_results.items():
135
+ results.append({"score": float(score), "file": filepath})
136
+
137
+ return json.dumps({"results": results})
138
+
139
+
140
+ demo = gr.Interface(
141
+ fn=respond,
142
+ inputs=[
143
+ gr.File(type="filepath", label="Upload .zip Folder"),
144
+ gr.Textbox(label="Enter your query")
 
 
 
 
 
 
 
145
  ],
146
+ outputs=gr.JSON(),
147
  )
148
 
 
149
  if __name__ == "__main__":
150
+ demo.launch(share=True)