File size: 8,726 Bytes
f1a04ea
 
 
 
 
 
 
 
b868160
f1a04ea
 
b868160
f1a04ea
 
 
4ce93da
f1a04ea
 
a2b8ed7
 
f1a04ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2b8ed7
f1a04ea
 
 
 
 
 
86e3d75
f1a04ea
 
 
 
 
 
86e3d75
f1a04ea
 
 
 
 
 
86e3d75
f1a04ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86e3d75
6f31366
f1a04ea
 
 
 
 
 
 
6f31366
f1a04ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f31366
f1a04ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f31366
f1a04ea
 
6f31366
f1a04ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f31366
f1a04ea
 
 
 
 
 
6ab6544
f1a04ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab6544
4ce93da
f1a04ea
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from flask import Flask, request, jsonify
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.llms import HuggingFaceEndpoint
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
import os
from dotenv import load_dotenv
from flask_cors import CORS
import base64
import tempfile
import io
from pathlib import Path

# Load environment variables
load_dotenv()

app = Flask(__name__)
CORS(app)

# Increase maximum content length to 32MB
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024

# Global variables
qa_chain = None
vector_db = None
api_token =os.getenv("HF_TOKEN")
pdf_chunks = {}
app.config['UPLOAD_FOLDER'] = 'temp_uploads'

# Create upload folder if it doesn't exist
Path(app.config['UPLOAD_FOLDER']).mkdir(parents=True, exist_ok=True)

# Available LLM models
LLM_MODELS = {
    "llama": "meta-llama/Meta-Llama-3-8B-Instruct",
    "mistral": "mistralai/Mistral-7B-Instruct-v0.2"
}

# Add these global variables
current_upload = {
    'filename': None,
    'chunks': [],
    'filesize': 0
}

def load_doc(file_paths):
    """Load and split multiple PDF documents"""
    loaders = [PyPDFLoader(path) for path in file_paths]
    pages = []
    for loader in loaders:
        pages.extend(loader.load())

    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=1024,
        chunk_overlap=64
    )
    doc_splits = text_splitter.split_documents(pages)
    return doc_splits

def create_db(splits):
    """Create vector database from document splits"""
    embeddings = HuggingFaceEmbeddings()
    vectordb = FAISS.from_documents(splits, embeddings)
    return vectordb

def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
    """Initialize the LLM chain"""
    llm = HuggingFaceEndpoint(
        repo_id=llm_model,
        huggingfacehub_api_token=api_token,
        temperature=temperature,
        max_new_tokens=max_tokens,
        top_k=top_k,
    )

    memory = ConversationBufferMemory(
        memory_key="chat_history",
        output_key='answer',
        return_messages=True
    )

    retriever = vector_db.as_retriever()
    qa_chain = ConversationalRetrievalChain.from_llm(
        llm,
        retriever=retriever,
        chain_type="stuff",
        memory=memory,
        return_source_documents=True,
        verbose=False,
    )
    return qa_chain

def format_chat_history(message, chat_history):
    """Format chat history for the LLM"""
    formatted_chat_history = []
    for user_message, bot_message in chat_history:
        formatted_chat_history.append(f"User: {user_message}")
        formatted_chat_history.append(f"Assistant: {bot_message}")
    return formatted_chat_history

@app.route('/upload', methods=['POST'])
def upload_pdf():
    """Handle PDF upload and database initialization"""
    global vector_db

    if 'pdf_base64' not in request.json:
        return jsonify({'error': 'No PDF data provided'}), 400

    try:
        # Get base64 PDF and filename
        pdf_base64 = request.json['pdf_base64']
        filename = request.json.get('filename', 'uploaded.pdf')

        # Create temp directory if it doesn't exist
        os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
        temp_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)

        try:
            # Decode and save PDF
            pdf_data = base64.b64decode(pdf_base64)
            with open(temp_path, 'wb') as f:
                f.write(pdf_data)

            # Process document
            doc_splits = load_doc([temp_path])
            vector_db = create_db(doc_splits)

            return jsonify({'message': 'PDF processed successfully'}), 200
        finally:
            # Clean up
            if os.path.exists(temp_path):
                os.remove(temp_path)

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/initialize-llm', methods=['POST'])
def init_llm():
    """Initialize the LLM with parameters"""
    global qa_chain, vector_db

    if vector_db is None:
        return jsonify({'error': 'Please upload PDFs first'}), 400

    data = request.json
    model_name = data.get('model', 'llama')  # default to llama
    temperature = data.get('temperature', 0.5)
    max_tokens = data.get('max_tokens', 4096)
    top_k = data.get('top_k', 3)

    if model_name not in LLM_MODELS:
        return jsonify({'error': 'Invalid model name'}), 400

    try:
        qa_chain = initialize_llmchain(
            LLM_MODELS[model_name],
            temperature,
            max_tokens,
            top_k,
            vector_db
        )
        return jsonify({'message': 'LLM initialized successfully'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/chat', methods=['POST'])
def chat():
    """Handle chat interactions"""
    global qa_chain

    if qa_chain is None:
        return jsonify({'error': 'LLM not initialized'}), 400

    data = request.json
    question = data.get('question')
    chat_history = data.get('chat_history', [])

    if not question:
        return jsonify({'error': 'No question provided'}), 400

    try:
        formatted_history = format_chat_history(question, chat_history)
        result = qa_chain({"question": question, "chat_history": formatted_history})

        # Process the response
        answer = result['answer']
        if "Helpful Answer:" in answer:
            answer = answer.split("Helpful Answer:")[-1]

        # Extract sources
        sources = []
        for doc in result['source_documents'][:3]:
            sources.append({
                'content': doc.page_content.strip(),
                'page': doc.metadata.get('page', 0) + 1  # Convert to 1-based page numbers
            })

        response = {
            'answer': answer,
            'sources': sources
        }

        return jsonify(response), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/upload-local', methods=['POST'])
def upload_local():
    """Handle PDF upload from local file system"""
    global vector_db

    data = request.json
    file_path = data.get('file_path')

    if not file_path or not os.path.exists(file_path):
        return jsonify({'error': 'File not found'}), 400

    try:
        # Process document
        doc_splits = load_doc([file_path])
        vector_db = create_db(doc_splits)

        return jsonify({'message': 'PDF processed successfully'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/start-upload', methods=['POST'])
def start_upload():
    """Initialize a new file upload"""
    global current_upload

    data = request.json
    current_upload = {
        'filename': data['filename'],
        'chunks': [],
        'filesize': data['filesize']
    }
    return jsonify({'message': 'Upload started'}), 200

@app.route('/upload-chunk', methods=['POST'])
def upload_chunk():
    """Handle a chunk of the file"""
    global current_upload

    if not current_upload['filename']:
        return jsonify({'error': 'No upload in progress'}), 400

    try:
        chunk = base64.b64decode(request.json['chunk'])
        current_upload['chunks'].append(chunk)
        return jsonify({'message': 'Chunk received'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/finish-upload', methods=['POST'])
def finish_upload():
    """Process the complete file"""
    global current_upload, vector_db

    if not current_upload['filename']:
        return jsonify({'error': 'No upload in progress'}), 400
    
    try:
        # Create temp directory if it doesn't exist
        os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
        temp_path = os.path.join(app.config['UPLOAD_FOLDER'], current_upload['filename'])

        # Combine chunks and save file
        with open(temp_path, 'wb') as f:
            for chunk in current_upload['chunks']:
                f.write(chunk)

        # Process the PDF
        doc_splits = load_doc([temp_path])
        vector_db = create_db(doc_splits)

        # Cleanup
        os.remove(temp_path)
        current_upload['chunks'] = []
        current_upload['filename'] = None

        return jsonify({'message': 'PDF processed successfully'}), 200
    except Exception as e:
        if os.path.exists(temp_path):
            os.remove(temp_path)
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)