temp / app.py
jawakja's picture
Upload app.py
588898e verified
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)