File size: 4,340 Bytes
0fe2abc
 
635f248
 
 
19855be
 
 
 
0fe2abc
 
19855be
 
 
caea9a5
39986c9
caea9a5
19855be
 
 
 
 
39986c9
19855be
 
 
 
635f248
19855be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635f248
19855be
 
 
635f248
19855be
635f248
19855be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe2abc
19855be
0fe2abc
 
 
19855be
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import gradio as gr
from huggingface_hub import InferenceClient
import os 
import pandas as pd 
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
from huggingface_hub import HfApi
import zipfile
import json


from sklearn.metrics.pairwise import cosine_similarity





api = HfApi()

models = api.list_models()
print(models)

client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")

class InformationRetrieval:
    def __init__(self, filepaths):
  
        self.text_data = []
        self.filepaths = filepaths
        try:
            for filepath in self.filepaths:
     
                try:
                    with open(filepath, 'r', encoding='utf-8') as file:
                        content = file.read()
                except UnicodeDecodeError:
                    with open(filepath, 'r', encoding='ISO-8859-1') as file:
                        content = file.read()
                self.text_data.append(content)
            print("Files loaded successfully.")
        except Exception as e:
            print(f"Error reading files: {e}")
            self.text_data = []

     
        try:
            self.model = SentenceTransformer('all-MiniLM-L6-v2')
            print("Sentence Transformer model loaded successfully.")
        except Exception as e:
            print(f"Error loading model: {e}")
            self.model = None
    def encode_and_retrieve(self, query):
        if not query:
            query = "default text"

        if not self.model:
            print("Model is not initialized.")
            return {}

        try:
            query_embedding = self.model.encode([query])
            query_embedding = query_embedding.reshape(1, -1)
        except Exception as e:
            print(f"Error encoding query: {e}")
            return {}

        embeddings_dict = {}

        for i, text in enumerate(self.text_data):
            try:
                truncated_text = text[:1000]

                doc_embedding = self.model.encode([truncated_text])

                if doc_embedding.ndim == 3:
                    doc_embedding = doc_embedding.reshape(doc_embedding.shape[0], -1)
                elif doc_embedding.ndim == 1:
                    doc_embedding = doc_embedding.reshape(1, -1)

                similarity = cosine_similarity(query_embedding, doc_embedding)[0][0]
                embeddings_dict[self.filepaths[i]] = similarity
            except Exception as e:
                print(f"Error processing document {self.filepaths[i]}: {e}")

        sorted_embeddings = sorted(embeddings_dict.items(), key=lambda item: item[1], reverse=True)

        result_dict = {path: score for path, score in sorted_embeddings}
        return result_dict



def process_zip_file(zip_file):
    try:
        zip_filepath = zip_file.name
        filepaths = []
        with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
            zip_ref.extractall("extracted_files")
            for filename in zip_ref.namelist():
                if filename.startswith('__MACOSX/') or filename.startswith('._'):
                    continue
                if filename.endswith('.txt'):
                    filepaths.append(os.path.join("extracted_files", filename))
        return {"files": filepaths}
    except Exception as e:
        return {"error": f"Error processing zip file: {e}"}



def respond(zip_file, query):
    if zip_file is None:
        return {"error": "Please upload a .zip file containing the data."}

    filepaths = process_zip_file(zip_file)
    if "error" in filepaths:
        return filepaths  

    extracted_files = filepaths["files"]
    print(f"Extracted files: {extracted_files}")

    ir_model = InformationRetrieval(extracted_files)
  
    ir_results = ir_model.encode_and_retrieve(query)

    if not ir_results:
        return json.dumps({"error": "No results found for the given query."})

    results = []
    for filepath, score in ir_results.items():
        results.append({"score": float(score), "file": filepath})

    return json.dumps({"results": results})


demo = gr.Interface(
    fn=respond,
    inputs=[
        gr.File(type="filepath", label="Upload .zip Folder"),  
        gr.Textbox(label="Enter your query")  
    ],
    outputs=gr.JSON(), 
)

if __name__ == "__main__":
    demo.launch(share=True)