File size: 1,651 Bytes
588898e |
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 |
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import os
from werkzeug.utils import secure_filename
from chat_pdf import ChatPDF #importing ChatPDF class
app = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
# Ensure upload directory exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Initialize ChatPDF
chat_pdf = ChatPDF()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file and file.filename.endswith('.pdf'):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Process the file with ChatPDF
chat_pdf.ingest(file_path=filepath, file_name=filename)
return jsonify({'message': 'File uploaded successfully'}), 200
return jsonify({'error': 'Invalid file type'}), 400
@app.route('/chat', methods=['POST'])
def chat():
data = request.json
if not data or 'message' not in data:
return jsonify({'error': 'No message provided'}), 400
response = chat_pdf.ask(data['message'])
return jsonify({'response': response}), 200
if __name__ == '__main__':
app.run(debug=True) |