File size: 6,219 Bytes
7037dda
 
 
 
 
 
 
 
 
 
0a74639
7037dda
 
 
 
77b95d4
 
 
 
 
 
 
7037dda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import os
import zipfile
import json
from fileconverter import convert_pdf_file_to_txt_file
from docx import Document
import gradio as gr
from dotenv import load_dotenv
from huggingface_hub import InferenceClient
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
from huggingface_hub import HfApi




api = HfApi()

models = api.list_models()
print(models)

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


MAX_FILE_SIZE_MB = 100  


class InformationRetrieval:
    def __init__(self, filepaths):
        self.text_data = []
        self.filepaths = filepaths

        for filepath in self.filepaths:
            try:
               
                content = self.read_file_with_encoding(filepath, 'utf-8')
            except (UnicodeDecodeError, ValueError):
                content = self.read_binary_or_convert(filepath)
            if not content.startswith("Error processing file"):
                self.text_data.append(content)

        self.model = SentenceTransformer('all-MiniLM-L6-v2')

    def read_file_with_encoding(self, filepath, encoding):
        try:
            with open(filepath, 'r', encoding=encoding, errors='ignore') as file:
                return file.read()
        except Exception as e:
            print(f"Error reading {filepath} with encoding {encoding}: {e}")
            raise e

    def read_binary_or_convert(self, filepath):
        try:
            if filepath.lower().endswith('.pdf'):
                return convert_pdf_file_to_txt_file(filepath)
            elif filepath.lower().endswith('.docx'):
                return self.convert_docx_file_to_txt_file(filepath)
            else:
                with open(filepath, 'rb') as file:
                    return file.read(512).decode(errors='ignore')  
        except Exception as e:
            print(f"Error converting {filepath}: {e}")
            return f"Error processing file: {filepath}"

    @staticmethod
    def convert_docx_file_to_txt_file(filepath):
        try:
            doc = Document(filepath)
            return "\n".join(paragraph.text for paragraph in doc.paragraphs)
        except Exception as e:
            print(f"Error converting DOCX file {filepath}: {e}")
            return f"Error processing DOCX file: {filepath}"

    def encode_and_retrieve(self, query):
        if not self.model:
            return {"error": "Model initialization failed."}

        query_embedding = self.model.encode([query]).reshape(1, -1)
        embeddings_dict = {}

        for i, text in enumerate(self.text_data):
            truncated_text = text[:1000]
            doc_embedding = self.model.encode([truncated_text]).reshape(1, -1)
            similarity = cosine_similarity(query_embedding, doc_embedding)[0][0]
            embeddings_dict[self.filepaths[i]] = similarity

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


def process_zip_file(zip_file):
    if not os.path.exists("extracted_files"):
        os.makedirs("extracted_files")

    try:
        with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
            zip_ref.extractall("extracted_files")
            filepaths = []
            total_size = 0  
            for filename in zip_ref.namelist():
                if "__MACOSX" in filename or filename.startswith(".DS_Store") or filename.startswith("."):
                    continue

                file_path = os.path.join("extracted_files", filename)

                if os.path.isdir(file_path):
                    continue

                total_size += os.path.getsize(file_path)  

                if total_size > MAX_FILE_SIZE_MB * 1024 * 1024:
                    return {"error": f"Total file size exceeds {MAX_FILE_SIZE_MB}MB. Please upload smaller files."}

                filepaths.append(file_path)

            return filepaths  
    except Exception as e:
        return {"error": str(e)}


class ChatBot:
    def __init__(self, text_data):
        self.text_data = "\n".join(text_data)

    def answer_question(self, question):
        prompt = f"Given the following text data, answer the question:\n\n{self.text_data}\n\nQuestion: {question}\nAnswer:"

        try:
            response = client.text_generation(prompt)

            generated_text = response.get("generated_text", "No response generated")

            return generated_text

        except Exception as e:
            return f"An error occurred: {str(e)}"


def chatbot_response(zip_file, user_input):
    if not zip_file:
        return {"error": "No .zip file provided."}

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

    ir_model = InformationRetrieval(filepaths)
    chatbot = ChatBot(ir_model.text_data)

    response = chatbot.answer_question(user_input)
    return response


def respond(zip_file, user_input):
    if not zip_file:
        return {"error": "No .zip file provided."}

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

    ir_model = InformationRetrieval(filepaths)
    return ir_model.encode_and_retrieve(user_input)


demo = gr.Blocks()

with demo:
    gr.Markdown("### Document Information Retrieval and Chatbot")

    with gr.Tab("Upload Files and Retrieve Info"):
        with gr.Row():
            zip_input = gr.File(type="filepath", label="Upload .zip Folder")
            query_input = gr.Textbox(label="Enter your query")
        retrieve_button = gr.Button("Retrieve")
        retrieve_output = gr.JSON(label="Results")

        retrieve_button.click(
            fn=respond,
            inputs=[zip_input, query_input],
            outputs=retrieve_output
        )

    with gr.Tab("Chatbot"):
        with gr.Row():
            zip_input_chat = gr.File(type="filepath", label="Upload .zip Folder")
            chat_input = gr.Textbox(label="Ask a question")
        chat_button = gr.Button("Ask")
        chat_output = gr.Textbox(label="Chatbot Response")

        chat_button.click(
            fn=chatbot_response,
            inputs=[zip_input_chat, chat_input],
            outputs=chat_output
        )

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