Spaces:
Sleeping
Sleeping
| import os | |
| import uuid | |
| import sqlite3 | |
| from flask import Flask, request, jsonify, session, send_from_directory | |
| from werkzeug.utils import secure_filename | |
| from werkzeug.security import generate_password_hash, check_password_hash | |
| from flask_cors import CORS | |
| import PyPDF2 | |
| import pandas as pd | |
| app = Flask(__name__) | |
| CORS(app) | |
| app.secret_key = 'your_secret_key_here' | |
| UPLOAD_FOLDER = 'uploads' | |
| ALLOWED_EXTENSIONS = {'pdf', 'csv', 'txt'} | |
| app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER | |
| # Ensure upload folder exists | |
| os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
| # === DATABASE SETUP === | |
| def init_db(): | |
| with sqlite3.connect('users.db') as conn: | |
| conn.execute('''CREATE TABLE IF NOT EXISTS users ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| email TEXT UNIQUE NOT NULL, | |
| username TEXT UNIQUE NOT NULL, | |
| password TEXT NOT NULL | |
| )''') | |
| init_db() | |
| # === HELPERS === | |
| def allowed_file(filename): | |
| return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | |
| def extract_text_from_pdf(file_path): | |
| text = "" | |
| with open(file_path, 'rb') as f: | |
| reader = PyPDF2.PdfReader(f) | |
| for page in reader.pages: | |
| text += page.extract_text() or "" | |
| return text | |
| def extract_text_from_csv(file_path): | |
| df = pd.read_csv(file_path) | |
| return df.to_string(index=False) | |
| # === ROUTES === | |
| def index(): | |
| return send_from_directory('.', 'index.html') | |
| def static_proxy(path): | |
| return send_from_directory('.', path) | |
| def register(): | |
| data = request.json | |
| email = data.get('email') | |
| username = data.get('username') | |
| password = generate_password_hash(data.get('password')) | |
| with sqlite3.connect('users.db') as conn: | |
| try: | |
| conn.execute("INSERT INTO users (email, username, password) VALUES (?, ?, ?)", | |
| (email, username, password)) | |
| return jsonify({'message': 'User registered successfully'}), 201 | |
| except sqlite3.IntegrityError: | |
| return jsonify({'error': 'Email or username already exists'}), 409 | |
| def login(): | |
| data = request.json | |
| username = data.get('username') | |
| password = data.get('password') | |
| with sqlite3.connect('users.db') as conn: | |
| user = conn.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone() | |
| if user and check_password_hash(user[3], password): | |
| session['user_id'] = user[0] | |
| return jsonify({'message': 'Login successful'}) | |
| return jsonify({'error': 'Invalid credentials'}), 401 | |
| def upload_file(): | |
| if 'file' not in request.files: | |
| return jsonify({'error': 'No file part'}), 400 | |
| file = request.files['file'] | |
| if file and allowed_file(file.filename): | |
| filename = secure_filename(file.filename) | |
| file_id = str(uuid.uuid4()) + "_" + filename | |
| file_path = os.path.join(app.config['UPLOAD_FOLDER'], file_id) | |
| file.save(file_path) | |
| if filename.endswith('.pdf'): | |
| text = extract_text_from_pdf(file_path) | |
| elif filename.endswith('.csv'): | |
| text = extract_text_from_csv(file_path) | |
| else: | |
| text = file.read().decode('utf-8') | |
| return jsonify({'extracted_text': text}) | |
| return jsonify({'error': 'Invalid file type'}), 400 | |
| def logout(): | |
| session.clear() | |
| return jsonify({'message': 'Logged out successfully'}) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) | |