Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,621 +3,229 @@ import uuid
|
|
| 3 |
import datetime
|
| 4 |
import tempfile
|
| 5 |
import json
|
| 6 |
-
from flask import Flask, request, jsonify, redirect
|
| 7 |
from flask_cors import CORS
|
| 8 |
from werkzeug.utils import secure_filename
|
| 9 |
from huggingface_hub import HfApi
|
| 10 |
-
import requests
|
| 11 |
-
from io import BytesIO
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
CORS(app)
|
| 15 |
|
| 16 |
-
#
|
| 17 |
ALLOWED_EXTENSIONS = {'pdf', 'epub', 'txt', 'docx'}
|
| 18 |
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB
|
| 19 |
|
| 20 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
# Metadata file stored in the dataset
|
| 24 |
-
METADATA_FILE = "metadata.json"
|
| 25 |
|
| 26 |
api = HfApi()
|
| 27 |
|
| 28 |
-
# ===== HELPERS =====
|
| 29 |
-
|
| 30 |
def allowed_file(filename):
|
| 31 |
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 32 |
|
| 33 |
-
def get_file_size_format(size_bytes):
|
| 34 |
-
"""Convert file size to human readable format"""
|
| 35 |
-
if size_bytes < 1024:
|
| 36 |
-
return f"{size_bytes} B"
|
| 37 |
-
elif size_bytes < 1024 * 1024:
|
| 38 |
-
return f"{size_bytes / 1024:.2f} KB"
|
| 39 |
-
else:
|
| 40 |
-
return f"{size_bytes / (1024 * 1024):.2f} MB"
|
| 41 |
-
|
| 42 |
def load_metadata():
|
| 43 |
-
"""Load metadata from
|
| 44 |
try:
|
| 45 |
-
# Try to download metadata file
|
| 46 |
-
metadata_url = f"https://huggingface.co/datasets/{
|
|
|
|
| 47 |
response = requests.get(metadata_url)
|
| 48 |
-
|
| 49 |
if response.status_code == 200:
|
| 50 |
return response.json()
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
except Exception as e:
|
| 55 |
-
print(f"Error loading metadata: {e}")
|
| 56 |
-
return {}
|
| 57 |
|
| 58 |
def save_metadata(metadata):
|
| 59 |
-
"""Save metadata to
|
| 60 |
try:
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
json.dump(metadata, tmp, indent=2)
|
| 64 |
tmp_path = tmp.name
|
| 65 |
|
| 66 |
-
# Upload metadata file to dataset
|
| 67 |
api.upload_file(
|
| 68 |
path_or_fileobj=tmp_path,
|
| 69 |
-
path_in_repo=
|
| 70 |
-
repo_id=
|
| 71 |
repo_type="dataset",
|
| 72 |
token=HF_TOKEN
|
| 73 |
)
|
| 74 |
-
|
| 75 |
os.remove(tmp_path)
|
| 76 |
return True
|
| 77 |
-
except
|
| 78 |
-
print(f"Error saving metadata: {e}")
|
| 79 |
return False
|
| 80 |
|
| 81 |
-
def update_ebook_metadata(ebook_id, updates):
|
| 82 |
-
"""Update specific ebook metadata"""
|
| 83 |
-
metadata = load_metadata()
|
| 84 |
-
if ebook_id in metadata:
|
| 85 |
-
metadata[ebook_id].update(updates)
|
| 86 |
-
return save_metadata(metadata)
|
| 87 |
-
return False
|
| 88 |
-
|
| 89 |
-
def get_ebook_metadata(ebook_id):
|
| 90 |
-
"""Get metadata for specific ebook"""
|
| 91 |
-
metadata = load_metadata()
|
| 92 |
-
return metadata.get(ebook_id)
|
| 93 |
-
|
| 94 |
-
def get_file_from_hf(file_path):
|
| 95 |
-
"""Download file from Hugging Face dataset"""
|
| 96 |
-
try:
|
| 97 |
-
file_url = f"https://huggingface.co/datasets/{HF_DATASET_REPO}/resolve/main/{file_path}"
|
| 98 |
-
response = requests.get(file_url, stream=True)
|
| 99 |
-
if response.status_code == 200:
|
| 100 |
-
return BytesIO(response.content)
|
| 101 |
-
return None
|
| 102 |
-
except Exception as e:
|
| 103 |
-
print(f"Error downloading file: {e}")
|
| 104 |
-
return None
|
| 105 |
-
|
| 106 |
-
# Default cover images for eBooks
|
| 107 |
-
DEFAULT_COVERS = [
|
| 108 |
-
"https://images.unsplash.com/photo-1512820790803-83ca734da794?w=500",
|
| 109 |
-
"https://images.unsplash.com/photo-1495446815901-a7297e633e8d?w=500",
|
| 110 |
-
"https://images.unsplash.com/photo-1532012197267-da84d127e765?w=500",
|
| 111 |
-
"https://images.unsplash.com/photo-1456513080510-7bf3a84b82f8?w=500",
|
| 112 |
-
"https://images.unsplash.com/photo-1524995997946-a1c2e315a42f?w=500",
|
| 113 |
-
"https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?w=500",
|
| 114 |
-
"https://images.unsplash.com/photo-1526243741027-444d633d7365?w=500"
|
| 115 |
-
]
|
| 116 |
-
|
| 117 |
-
# ===== UPLOAD API =====
|
| 118 |
-
|
| 119 |
@app.route('/api/upload', methods=['POST'])
|
| 120 |
def upload_ebook():
|
|
|
|
| 121 |
try:
|
| 122 |
if 'file' not in request.files:
|
| 123 |
return jsonify({'error': 'No file provided'}), 400
|
| 124 |
-
|
| 125 |
file = request.files['file']
|
| 126 |
-
|
| 127 |
if file.filename == '':
|
| 128 |
return jsonify({'error': 'No file selected'}), 400
|
| 129 |
-
|
| 130 |
if not allowed_file(file.filename):
|
| 131 |
-
return jsonify({'error':
|
| 132 |
-
|
| 133 |
if not HF_TOKEN:
|
| 134 |
return jsonify({'error': 'HF_TOKEN not configured'}), 500
|
| 135 |
-
|
| 136 |
-
#
|
| 137 |
-
title = request.form.get('title', '')
|
| 138 |
-
author = request.form.get('author', '')
|
| 139 |
category = request.form.get('category', 'General')
|
| 140 |
-
uploaded_by = request.form.get('uploaded_by', '')
|
| 141 |
-
image_url = request.form.get('image_url', '')
|
| 142 |
-
|
| 143 |
if not uploaded_by:
|
| 144 |
return jsonify({'error': 'User ID required'}), 400
|
| 145 |
-
|
| 146 |
-
# Generate unique ID and filename
|
| 147 |
-
unique_id = str(uuid.uuid4())
|
| 148 |
-
original_filename = secure_filename(file.filename)
|
| 149 |
-
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 150 |
-
filename = f"{timestamp}_{unique_id}_{original_filename}"
|
| 151 |
-
file_path = f"ebooks/{filename}"
|
| 152 |
-
|
| 153 |
# Save temporarily
|
| 154 |
with tempfile.NamedTemporaryFile(delete=False) as tmp:
|
| 155 |
file.save(tmp.name)
|
| 156 |
temp_path = tmp.name
|
| 157 |
-
|
| 158 |
file_size = os.path.getsize(temp_path)
|
| 159 |
-
|
| 160 |
-
|
| 161 |
if file_size > MAX_FILE_SIZE:
|
| 162 |
os.remove(temp_path)
|
| 163 |
-
return jsonify({'error':
|
| 164 |
-
|
| 165 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
api.upload_file(
|
| 167 |
path_or_fileobj=temp_path,
|
| 168 |
-
path_in_repo=
|
| 169 |
-
repo_id=
|
| 170 |
repo_type="dataset",
|
| 171 |
token=HF_TOKEN
|
| 172 |
)
|
| 173 |
-
|
| 174 |
os.remove(temp_path)
|
| 175 |
-
|
| 176 |
-
#
|
| 177 |
-
file_url = f"https://huggingface.co/datasets/{
|
| 178 |
-
|
| 179 |
-
# Select random default cover if no image URL provided
|
| 180 |
-
if not image_url:
|
| 181 |
-
import random
|
| 182 |
-
image_url = random.choice(DEFAULT_COVERS)
|
| 183 |
-
|
| 184 |
# Create metadata
|
| 185 |
ebook_metadata = {
|
| 186 |
'id': unique_id,
|
| 187 |
'filename': original_filename,
|
| 188 |
-
'
|
| 189 |
-
'stored_path': file_path,
|
| 190 |
'title': title or original_filename,
|
| 191 |
'author': author or 'Unknown',
|
| 192 |
'category': category,
|
| 193 |
'image_url': image_url,
|
| 194 |
'uploaded_by': uploaded_by,
|
| 195 |
'size': file_size,
|
| 196 |
-
'size_formatted': size_formatted,
|
| 197 |
'upload_date': datetime.datetime.now().isoformat(),
|
| 198 |
-
'last_accessed': None,
|
| 199 |
'download_count': 0,
|
| 200 |
-
'file_extension': original_filename.rsplit('.', 1)[1].lower(),
|
| 201 |
'download_url': file_url
|
| 202 |
}
|
| 203 |
-
|
| 204 |
-
#
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
# If metadata save failed, try to delete the uploaded file
|
| 215 |
-
try:
|
| 216 |
-
api.delete_file(
|
| 217 |
-
path_in_repo=file_path,
|
| 218 |
-
repo_id=HF_DATASET_REPO,
|
| 219 |
-
repo_type="dataset",
|
| 220 |
-
token=HF_TOKEN
|
| 221 |
-
)
|
| 222 |
-
except:
|
| 223 |
-
pass
|
| 224 |
-
return jsonify({'error': 'Failed to save metadata'}), 500
|
| 225 |
-
|
| 226 |
except Exception as e:
|
| 227 |
return jsonify({'error': str(e)}), 500
|
| 228 |
|
| 229 |
-
|
| 230 |
-
# ===== LIST EBOOKS =====
|
| 231 |
-
|
| 232 |
@app.route('/api/ebooks', methods=['GET'])
|
| 233 |
def list_ebooks():
|
|
|
|
| 234 |
try:
|
| 235 |
metadata = load_metadata()
|
| 236 |
-
|
| 237 |
-
# Convert metadata dict to list
|
| 238 |
-
ebook_list = []
|
| 239 |
-
for ebook_id, ebook_data in metadata.items():
|
| 240 |
-
ebook_info = ebook_data.copy()
|
| 241 |
-
# Ensure download URL is present
|
| 242 |
-
if 'download_url' not in ebook_info:
|
| 243 |
-
ebook_info['download_url'] = f"https://huggingface.co/datasets/{HF_DATASET_REPO}/resolve/main/{ebook_info.get('stored_path', f'ebooks/{ebook_info["stored_filename"]}')}"
|
| 244 |
-
ebook_list.append(ebook_info)
|
| 245 |
-
|
| 246 |
-
# Sort by upload date (newest first)
|
| 247 |
ebook_list.sort(key=lambda x: x.get('upload_date', ''), reverse=True)
|
| 248 |
-
|
| 249 |
return jsonify(ebook_list), 200
|
| 250 |
-
|
| 251 |
except Exception as e:
|
| 252 |
return jsonify({'error': str(e)}), 500
|
| 253 |
|
| 254 |
-
|
| 255 |
-
# ===== GET SINGLE EBOOK =====
|
| 256 |
-
|
| 257 |
-
@app.route('/api/ebooks/<ebook_id>', methods=['GET'])
|
| 258 |
-
def get_ebook(ebook_id):
|
| 259 |
-
try:
|
| 260 |
-
metadata = load_metadata()
|
| 261 |
-
|
| 262 |
-
if ebook_id not in metadata:
|
| 263 |
-
return jsonify({'error': 'eBook not found'}), 404
|
| 264 |
-
|
| 265 |
-
ebook_data = metadata[ebook_id]
|
| 266 |
-
# Ensure download URL is present
|
| 267 |
-
if 'download_url' not in ebook_data:
|
| 268 |
-
ebook_data['download_url'] = f"https://huggingface.co/datasets/{HF_DATASET_REPO}/resolve/main/{ebook_data.get('stored_path', f'ebooks/{ebook_data["stored_filename"]}')}"
|
| 269 |
-
|
| 270 |
-
return jsonify(ebook_data), 200
|
| 271 |
-
|
| 272 |
-
except Exception as e:
|
| 273 |
-
return jsonify({'error': str(e)}), 500
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
# ===== DOWNLOAD EBOOK =====
|
| 277 |
-
|
| 278 |
@app.route('/api/download/<ebook_id>', methods=['GET'])
|
| 279 |
def download_ebook(ebook_id):
|
|
|
|
| 280 |
try:
|
| 281 |
metadata = load_metadata()
|
| 282 |
-
|
| 283 |
if ebook_id not in metadata:
|
| 284 |
return jsonify({'error': 'eBook not found'}), 404
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
# Get file path
|
| 289 |
-
if 'stored_path' in ebook_data:
|
| 290 |
-
file_path = ebook_data['stored_path']
|
| 291 |
-
else:
|
| 292 |
-
file_path = f"ebooks/{ebook_data['stored_filename']}"
|
| 293 |
|
| 294 |
# Increment download count
|
| 295 |
-
|
| 296 |
-
ebook_data['last_accessed'] = datetime.datetime.now().isoformat()
|
| 297 |
-
|
| 298 |
-
# Update metadata
|
| 299 |
-
metadata[ebook_id] = ebook_data
|
| 300 |
save_metadata(metadata)
|
| 301 |
|
| 302 |
# Redirect to direct file URL
|
| 303 |
-
|
| 304 |
-
return redirect(file_url)
|
| 305 |
-
|
| 306 |
-
except Exception as e:
|
| 307 |
-
return jsonify({'error': str(e)}), 500
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
# ===== DIRECT DOWNLOAD (returns file) =====
|
| 311 |
-
|
| 312 |
-
@app.route('/api/direct-download/<ebook_id>', methods=['GET'])
|
| 313 |
-
def direct_download_ebook(ebook_id):
|
| 314 |
-
try:
|
| 315 |
-
metadata = load_metadata()
|
| 316 |
-
|
| 317 |
-
if ebook_id not in metadata:
|
| 318 |
-
return jsonify({'error': 'eBook not found'}), 404
|
| 319 |
-
|
| 320 |
-
ebook_data = metadata[ebook_id]
|
| 321 |
-
|
| 322 |
-
# Get file path
|
| 323 |
-
if 'stored_path' in ebook_data:
|
| 324 |
-
file_path = ebook_data['stored_path']
|
| 325 |
-
else:
|
| 326 |
-
file_path = f"ebooks/{ebook_data['stored_filename']}"
|
| 327 |
-
|
| 328 |
-
# Download file from HF
|
| 329 |
-
file_content = get_file_from_hf(file_path)
|
| 330 |
-
|
| 331 |
-
if file_content is None:
|
| 332 |
-
return jsonify({'error': 'File not found on server'}), 404
|
| 333 |
|
| 334 |
-
# Increment download count
|
| 335 |
-
ebook_data['download_count'] = ebook_data.get('download_count', 0) + 1
|
| 336 |
-
ebook_data['last_accessed'] = datetime.datetime.now().isoformat()
|
| 337 |
-
|
| 338 |
-
# Update metadata
|
| 339 |
-
metadata[ebook_id] = ebook_data
|
| 340 |
-
save_metadata(metadata)
|
| 341 |
-
|
| 342 |
-
# Send file
|
| 343 |
-
file_content.seek(0)
|
| 344 |
-
return send_file(
|
| 345 |
-
file_content,
|
| 346 |
-
as_attachment=True,
|
| 347 |
-
download_name=ebook_data['filename'],
|
| 348 |
-
mimetype='application/octet-stream'
|
| 349 |
-
)
|
| 350 |
-
|
| 351 |
except Exception as e:
|
| 352 |
return jsonify({'error': str(e)}), 500
|
| 353 |
|
| 354 |
-
|
| 355 |
-
# ===== DELETE EBOOK =====
|
| 356 |
-
|
| 357 |
@app.route('/api/ebooks/<ebook_id>', methods=['DELETE'])
|
| 358 |
def delete_ebook(ebook_id):
|
|
|
|
| 359 |
try:
|
| 360 |
data = request.get_json()
|
| 361 |
-
user_id = data.get('user_id')
|
| 362 |
|
| 363 |
if not user_id:
|
| 364 |
return jsonify({'error': 'User ID required'}), 400
|
| 365 |
-
|
| 366 |
metadata = load_metadata()
|
| 367 |
|
| 368 |
if ebook_id not in metadata:
|
| 369 |
return jsonify({'error': 'eBook not found'}), 404
|
|
|
|
|
|
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
# Get file path
|
| 378 |
-
if 'stored_path' in ebook_data:
|
| 379 |
-
file_path = ebook_data['stored_path']
|
| 380 |
-
else:
|
| 381 |
-
file_path = f"ebooks/{ebook_data['stored_filename']}"
|
| 382 |
-
|
| 383 |
-
# Delete file from HF Dataset
|
| 384 |
try:
|
| 385 |
api.delete_file(
|
| 386 |
-
path_in_repo=
|
| 387 |
-
repo_id=
|
| 388 |
repo_type="dataset",
|
| 389 |
token=HF_TOKEN
|
| 390 |
)
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
print(f"Error deleting file: {e}")
|
| 395 |
-
|
| 396 |
# Remove from metadata
|
| 397 |
del metadata[ebook_id]
|
|
|
|
| 398 |
|
| 399 |
-
|
| 400 |
-
return jsonify({
|
| 401 |
-
'message': 'eBook deleted successfully',
|
| 402 |
-
'file_deleted': file_deleted
|
| 403 |
-
}), 200
|
| 404 |
-
else:
|
| 405 |
-
return jsonify({'error': 'Failed to update metadata'}), 500
|
| 406 |
-
|
| 407 |
-
except Exception as e:
|
| 408 |
-
return jsonify({'error': str(e)}), 500
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
# ===== SEARCH EBOOKS =====
|
| 412 |
-
|
| 413 |
-
@app.route('/api/ebooks/search', methods=['GET'])
|
| 414 |
-
def search_ebooks():
|
| 415 |
-
try:
|
| 416 |
-
query = request.args.get('q', '').lower()
|
| 417 |
-
category = request.args.get('category', '')
|
| 418 |
-
|
| 419 |
-
metadata = load_metadata()
|
| 420 |
-
results = []
|
| 421 |
-
|
| 422 |
-
for ebook_id, ebook_data in metadata.items():
|
| 423 |
-
match = True
|
| 424 |
-
|
| 425 |
-
if query:
|
| 426 |
-
match = match and (
|
| 427 |
-
query in ebook_data.get('title', '').lower() or
|
| 428 |
-
query in ebook_data.get('author', '').lower() or
|
| 429 |
-
query in ebook_data.get('filename', '').lower()
|
| 430 |
-
)
|
| 431 |
-
|
| 432 |
-
if category:
|
| 433 |
-
match = match and category.lower() == ebook_data.get('category', '').lower()
|
| 434 |
-
|
| 435 |
-
if match:
|
| 436 |
-
ebook_info = ebook_data.copy()
|
| 437 |
-
if 'download_url' not in ebook_info:
|
| 438 |
-
ebook_info['download_url'] = f"https://huggingface.co/datasets/{HF_DATASET_REPO}/resolve/main/{ebook_info.get('stored_path', f'ebooks/{ebook_info["stored_filename"]}')}"
|
| 439 |
-
results.append(ebook_info)
|
| 440 |
-
|
| 441 |
-
return jsonify(results), 200
|
| 442 |
-
|
| 443 |
-
except Exception as e:
|
| 444 |
-
return jsonify({'error': str(e)}), 500
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
# ===== USER EBOOKS =====
|
| 448 |
-
|
| 449 |
-
@app.route('/api/ebooks/user/<user_id>', methods=['GET'])
|
| 450 |
-
def get_user_ebooks(user_id):
|
| 451 |
-
try:
|
| 452 |
-
metadata = load_metadata()
|
| 453 |
-
user_ebooks = []
|
| 454 |
-
|
| 455 |
-
for ebook_id, ebook_data in metadata.items():
|
| 456 |
-
if ebook_data.get('uploaded_by') == user_id:
|
| 457 |
-
ebook_info = ebook_data.copy()
|
| 458 |
-
if 'download_url' not in ebook_info:
|
| 459 |
-
ebook_info['download_url'] = f"https://huggingface.co/datasets/{HF_DATASET_REPO}/resolve/main/{ebook_info.get('stored_path', f'ebooks/{ebook_info["stored_filename"]}')}"
|
| 460 |
-
user_ebooks.append(ebook_info)
|
| 461 |
-
|
| 462 |
-
return jsonify(user_ebooks), 200
|
| 463 |
-
|
| 464 |
-
except Exception as e:
|
| 465 |
-
return jsonify({'error': str(e)}), 500
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
# ===== UPDATE EBOOK METADATA =====
|
| 469 |
-
|
| 470 |
-
@app.route('/api/ebooks/<ebook_id>', methods=['PUT'])
|
| 471 |
-
def update_ebook(ebook_id):
|
| 472 |
-
try:
|
| 473 |
-
data = request.get_json()
|
| 474 |
-
user_id = data.get('user_id')
|
| 475 |
-
|
| 476 |
-
if not user_id:
|
| 477 |
-
return jsonify({'error': 'User ID required'}), 400
|
| 478 |
-
|
| 479 |
-
metadata = load_metadata()
|
| 480 |
-
|
| 481 |
-
if ebook_id not in metadata:
|
| 482 |
-
return jsonify({'error': 'eBook not found'}), 404
|
| 483 |
-
|
| 484 |
-
ebook_data = metadata[ebook_id]
|
| 485 |
-
|
| 486 |
-
# Check if user is the uploader
|
| 487 |
-
if ebook_data['uploaded_by'] != user_id:
|
| 488 |
-
return jsonify({'error': 'Unauthorized: Only uploader can update'}), 403
|
| 489 |
-
|
| 490 |
-
# Update allowed fields
|
| 491 |
-
allowed_updates = ['title', 'author', 'category', 'image_url']
|
| 492 |
-
for field in allowed_updates:
|
| 493 |
-
if field in data:
|
| 494 |
-
ebook_data[field] = data[field]
|
| 495 |
-
|
| 496 |
-
# Save metadata
|
| 497 |
-
metadata[ebook_id] = ebook_data
|
| 498 |
|
| 499 |
-
if save_metadata(metadata):
|
| 500 |
-
return jsonify({
|
| 501 |
-
'message': 'eBook updated successfully',
|
| 502 |
-
'ebook': ebook_data
|
| 503 |
-
}), 200
|
| 504 |
-
else:
|
| 505 |
-
return jsonify({'error': 'Failed to update metadata'}), 500
|
| 506 |
-
|
| 507 |
except Exception as e:
|
| 508 |
return jsonify({'error': str(e)}), 500
|
| 509 |
|
| 510 |
-
|
| 511 |
-
# ===== STATISTICS =====
|
| 512 |
-
|
| 513 |
-
@app.route('/api/stats', methods=['GET'])
|
| 514 |
-
def get_stats():
|
| 515 |
-
try:
|
| 516 |
-
metadata = load_metadata()
|
| 517 |
-
|
| 518 |
-
total_size = 0
|
| 519 |
-
category_stats = {}
|
| 520 |
-
user_stats = {}
|
| 521 |
-
extension_stats = {}
|
| 522 |
-
total_downloads = 0
|
| 523 |
-
|
| 524 |
-
for ebook_data in metadata.values():
|
| 525 |
-
size = ebook_data.get('size', 0)
|
| 526 |
-
total_size += size
|
| 527 |
-
total_downloads += ebook_data.get('download_count', 0)
|
| 528 |
-
|
| 529 |
-
# Category statistics
|
| 530 |
-
category = ebook_data.get('category', 'General')
|
| 531 |
-
category_stats[category] = category_stats.get(category, 0) + 1
|
| 532 |
-
|
| 533 |
-
# User statistics
|
| 534 |
-
user = ebook_data.get('uploaded_by', 'unknown')
|
| 535 |
-
user_stats[user] = user_stats.get(user, 0) + 1
|
| 536 |
-
|
| 537 |
-
# File extension statistics
|
| 538 |
-
ext = ebook_data.get('file_extension', 'unknown')
|
| 539 |
-
extension_stats[ext] = extension_stats.get(ext, 0) + 1
|
| 540 |
-
|
| 541 |
-
return jsonify({
|
| 542 |
-
'total_ebooks': len(metadata),
|
| 543 |
-
'total_size_mb': round(total_size / (1024 * 1024), 2),
|
| 544 |
-
'total_downloads': total_downloads,
|
| 545 |
-
'category_distribution': category_stats,
|
| 546 |
-
'user_distribution': user_stats,
|
| 547 |
-
'file_type_distribution': extension_stats,
|
| 548 |
-
'dataset_repo': HF_DATASET_REPO
|
| 549 |
-
}), 200
|
| 550 |
-
|
| 551 |
-
except Exception as e:
|
| 552 |
-
return jsonify({'error': str(e)}), 500
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
# ===== HEALTH CHECK =====
|
| 556 |
-
|
| 557 |
@app.route('/api/health', methods=['GET'])
|
| 558 |
def health():
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
"status": "healthy",
|
| 565 |
-
"timestamp": datetime.datetime.now().isoformat(),
|
| 566 |
-
"dataset": HF_DATASET_REPO,
|
| 567 |
-
"total_ebooks": len(metadata),
|
| 568 |
-
"hf_token_configured": bool(HF_TOKEN)
|
| 569 |
-
}), 200
|
| 570 |
-
except Exception as e:
|
| 571 |
-
return jsonify({
|
| 572 |
-
"status": "unhealthy",
|
| 573 |
-
"error": str(e),
|
| 574 |
-
"dataset": HF_DATASET_REPO,
|
| 575 |
-
"hf_token_configured": bool(HF_TOKEN)
|
| 576 |
-
}), 500
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
# ===== INITIALIZE DATASET =====
|
| 580 |
-
|
| 581 |
-
@app.route('/api/init', methods=['POST'])
|
| 582 |
-
def initialize_dataset():
|
| 583 |
-
"""Initialize the dataset with metadata file if it doesn't exist"""
|
| 584 |
-
try:
|
| 585 |
-
# Check if metadata exists
|
| 586 |
-
metadata = load_metadata()
|
| 587 |
-
|
| 588 |
-
if not metadata:
|
| 589 |
-
# Create empty metadata
|
| 590 |
-
save_metadata({})
|
| 591 |
-
return jsonify({
|
| 592 |
-
'message': 'Dataset initialized successfully',
|
| 593 |
-
'metadata_created': True
|
| 594 |
-
}), 200
|
| 595 |
-
else:
|
| 596 |
-
return jsonify({
|
| 597 |
-
'message': 'Dataset already initialized',
|
| 598 |
-
'ebooks_count': len(metadata)
|
| 599 |
-
}), 200
|
| 600 |
-
|
| 601 |
-
except Exception as e:
|
| 602 |
-
return jsonify({'error': str(e)}), 500
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
# ===== RUN =====
|
| 606 |
|
| 607 |
if __name__ == '__main__':
|
| 608 |
port = int(os.environ.get('PORT', 7860))
|
| 609 |
-
|
| 610 |
-
print(f"🚀 Starting eBook Management Server with Hugging Face Dataset")
|
| 611 |
-
print(f"📚 Dataset: {HF_DATASET_REPO}")
|
| 612 |
-
print(f"🔑 HF Token configured: {bool(HF_TOKEN)}")
|
| 613 |
-
print(f"📁 Allowed file types: {', '.join(ALLOWED_EXTENSIONS)}")
|
| 614 |
-
print(f"📊 Max file size: {MAX_FILE_SIZE/1024/1024}MB")
|
| 615 |
-
|
| 616 |
-
# Try to initialize dataset on startup
|
| 617 |
-
try:
|
| 618 |
-
metadata = load_metadata()
|
| 619 |
-
print(f"✅ Loaded {len(metadata)} eBooks from dataset")
|
| 620 |
-
except Exception as e:
|
| 621 |
-
print(f"⚠️ Could not load metadata: {e}")
|
| 622 |
-
|
| 623 |
-
app.run(host='0.0.0.0', port=port, debug=False)
|
|
|
|
| 3 |
import datetime
|
| 4 |
import tempfile
|
| 5 |
import json
|
| 6 |
+
from flask import Flask, request, jsonify, redirect
|
| 7 |
from flask_cors import CORS
|
| 8 |
from werkzeug.utils import secure_filename
|
| 9 |
from huggingface_hub import HfApi
|
|
|
|
|
|
|
| 10 |
|
| 11 |
app = Flask(__name__)
|
| 12 |
CORS(app)
|
| 13 |
|
| 14 |
+
# Configuration
|
| 15 |
ALLOWED_EXTENSIONS = {'pdf', 'epub', 'txt', 'docx'}
|
| 16 |
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB
|
| 17 |
|
| 18 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 19 |
+
DATASET_REPO = os.environ.get("DATASET_REPO", "sivakumar330/Ebook")
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
api = HfApi()
|
| 22 |
|
|
|
|
|
|
|
| 23 |
def allowed_file(filename):
|
| 24 |
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def load_metadata():
|
| 27 |
+
"""Load all metadata from dataset"""
|
| 28 |
try:
|
| 29 |
+
# Try to download metadata file
|
| 30 |
+
metadata_url = f"https://huggingface.co/datasets/{DATASET_REPO}/resolve/main/all_metadata.json"
|
| 31 |
+
import requests
|
| 32 |
response = requests.get(metadata_url)
|
|
|
|
| 33 |
if response.status_code == 200:
|
| 34 |
return response.json()
|
| 35 |
+
except:
|
| 36 |
+
pass
|
| 37 |
+
return {}
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
def save_metadata(metadata):
|
| 40 |
+
"""Save metadata to dataset"""
|
| 41 |
try:
|
| 42 |
+
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp:
|
| 43 |
+
json.dump(metadata, tmp)
|
|
|
|
| 44 |
tmp_path = tmp.name
|
| 45 |
|
|
|
|
| 46 |
api.upload_file(
|
| 47 |
path_or_fileobj=tmp_path,
|
| 48 |
+
path_in_repo="all_metadata.json",
|
| 49 |
+
repo_id=DATASET_REPO,
|
| 50 |
repo_type="dataset",
|
| 51 |
token=HF_TOKEN
|
| 52 |
)
|
|
|
|
| 53 |
os.remove(tmp_path)
|
| 54 |
return True
|
| 55 |
+
except:
|
|
|
|
| 56 |
return False
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
@app.route('/api/upload', methods=['POST'])
|
| 59 |
def upload_ebook():
|
| 60 |
+
"""Upload ebook to Hugging Face dataset"""
|
| 61 |
try:
|
| 62 |
if 'file' not in request.files:
|
| 63 |
return jsonify({'error': 'No file provided'}), 400
|
| 64 |
+
|
| 65 |
file = request.files['file']
|
| 66 |
+
|
| 67 |
if file.filename == '':
|
| 68 |
return jsonify({'error': 'No file selected'}), 400
|
| 69 |
+
|
| 70 |
if not allowed_file(file.filename):
|
| 71 |
+
return jsonify({'error': 'Invalid file type'}), 400
|
| 72 |
+
|
| 73 |
if not HF_TOKEN:
|
| 74 |
return jsonify({'error': 'HF_TOKEN not configured'}), 500
|
| 75 |
+
|
| 76 |
+
# Get metadata
|
| 77 |
+
title = request.form.get('title', '')
|
| 78 |
+
author = request.form.get('author', '')
|
| 79 |
category = request.form.get('category', 'General')
|
| 80 |
+
uploaded_by = request.form.get('uploaded_by', '')
|
| 81 |
+
image_url = request.form.get('image_url', '')
|
| 82 |
+
|
| 83 |
if not uploaded_by:
|
| 84 |
return jsonify({'error': 'User ID required'}), 400
|
| 85 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
# Save temporarily
|
| 87 |
with tempfile.NamedTemporaryFile(delete=False) as tmp:
|
| 88 |
file.save(tmp.name)
|
| 89 |
temp_path = tmp.name
|
| 90 |
+
|
| 91 |
file_size = os.path.getsize(temp_path)
|
| 92 |
+
|
|
|
|
| 93 |
if file_size > MAX_FILE_SIZE:
|
| 94 |
os.remove(temp_path)
|
| 95 |
+
return jsonify({'error': 'File too large'}), 400
|
| 96 |
+
|
| 97 |
+
# Generate unique filename
|
| 98 |
+
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 99 |
+
unique_id = str(uuid.uuid4())
|
| 100 |
+
original_filename = secure_filename(file.filename)
|
| 101 |
+
year_month = datetime.datetime.now().strftime('%Y/%m')
|
| 102 |
+
|
| 103 |
+
filename = f"{timestamp}_{unique_id}_{original_filename}"
|
| 104 |
+
remote_path = f"ebooks/{year_month}/{filename}"
|
| 105 |
+
|
| 106 |
+
# Upload to dataset
|
| 107 |
api.upload_file(
|
| 108 |
path_or_fileobj=temp_path,
|
| 109 |
+
path_in_repo=remote_path,
|
| 110 |
+
repo_id=DATASET_REPO,
|
| 111 |
repo_type="dataset",
|
| 112 |
token=HF_TOKEN
|
| 113 |
)
|
| 114 |
+
|
| 115 |
os.remove(temp_path)
|
| 116 |
+
|
| 117 |
+
# Create download URL
|
| 118 |
+
file_url = f"https://huggingface.co/datasets/{DATASET_REPO}/resolve/main/{remote_path}"
|
| 119 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
# Create metadata
|
| 121 |
ebook_metadata = {
|
| 122 |
'id': unique_id,
|
| 123 |
'filename': original_filename,
|
| 124 |
+
'stored_path': remote_path,
|
|
|
|
| 125 |
'title': title or original_filename,
|
| 126 |
'author': author or 'Unknown',
|
| 127 |
'category': category,
|
| 128 |
'image_url': image_url,
|
| 129 |
'uploaded_by': uploaded_by,
|
| 130 |
'size': file_size,
|
|
|
|
| 131 |
'upload_date': datetime.datetime.now().isoformat(),
|
|
|
|
| 132 |
'download_count': 0,
|
|
|
|
| 133 |
'download_url': file_url
|
| 134 |
}
|
| 135 |
+
|
| 136 |
+
# Save to main metadata
|
| 137 |
+
all_metadata = load_metadata()
|
| 138 |
+
all_metadata[unique_id] = ebook_metadata
|
| 139 |
+
save_metadata(all_metadata)
|
| 140 |
+
|
| 141 |
+
return jsonify({
|
| 142 |
+
'message': 'Uploaded successfully to Hugging Face dataset',
|
| 143 |
+
'ebook': ebook_metadata
|
| 144 |
+
}), 201
|
| 145 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
except Exception as e:
|
| 147 |
return jsonify({'error': str(e)}), 500
|
| 148 |
|
|
|
|
|
|
|
|
|
|
| 149 |
@app.route('/api/ebooks', methods=['GET'])
|
| 150 |
def list_ebooks():
|
| 151 |
+
"""List all ebooks from dataset"""
|
| 152 |
try:
|
| 153 |
metadata = load_metadata()
|
| 154 |
+
ebook_list = list(metadata.values())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
ebook_list.sort(key=lambda x: x.get('upload_date', ''), reverse=True)
|
|
|
|
| 156 |
return jsonify(ebook_list), 200
|
|
|
|
| 157 |
except Exception as e:
|
| 158 |
return jsonify({'error': str(e)}), 500
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
@app.route('/api/download/<ebook_id>', methods=['GET'])
|
| 161 |
def download_ebook(ebook_id):
|
| 162 |
+
"""Redirect to dataset file URL"""
|
| 163 |
try:
|
| 164 |
metadata = load_metadata()
|
|
|
|
| 165 |
if ebook_id not in metadata:
|
| 166 |
return jsonify({'error': 'eBook not found'}), 404
|
| 167 |
+
|
| 168 |
+
ebook = metadata[ebook_id]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
# Increment download count
|
| 171 |
+
ebook['download_count'] = ebook.get('download_count', 0) + 1
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
save_metadata(metadata)
|
| 173 |
|
| 174 |
# Redirect to direct file URL
|
| 175 |
+
return redirect(ebook['download_url'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
except Exception as e:
|
| 178 |
return jsonify({'error': str(e)}), 500
|
| 179 |
|
|
|
|
|
|
|
|
|
|
| 180 |
@app.route('/api/ebooks/<ebook_id>', methods=['DELETE'])
|
| 181 |
def delete_ebook(ebook_id):
|
| 182 |
+
"""Delete ebook from dataset"""
|
| 183 |
try:
|
| 184 |
data = request.get_json()
|
| 185 |
+
user_id = data.get('user_id')
|
| 186 |
|
| 187 |
if not user_id:
|
| 188 |
return jsonify({'error': 'User ID required'}), 400
|
| 189 |
+
|
| 190 |
metadata = load_metadata()
|
| 191 |
|
| 192 |
if ebook_id not in metadata:
|
| 193 |
return jsonify({'error': 'eBook not found'}), 404
|
| 194 |
+
|
| 195 |
+
ebook = metadata[ebook_id]
|
| 196 |
|
| 197 |
+
# Check ownership
|
| 198 |
+
if ebook['uploaded_by'] != user_id:
|
| 199 |
+
return jsonify({'error': 'Unauthorized'}), 403
|
| 200 |
+
|
| 201 |
+
# Delete file from dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
try:
|
| 203 |
api.delete_file(
|
| 204 |
+
path_in_repo=ebook['stored_path'],
|
| 205 |
+
repo_id=DATASET_REPO,
|
| 206 |
repo_type="dataset",
|
| 207 |
token=HF_TOKEN
|
| 208 |
)
|
| 209 |
+
except:
|
| 210 |
+
pass # File might already be deleted
|
| 211 |
+
|
|
|
|
|
|
|
| 212 |
# Remove from metadata
|
| 213 |
del metadata[ebook_id]
|
| 214 |
+
save_metadata(metadata)
|
| 215 |
|
| 216 |
+
return jsonify({'message': 'eBook deleted successfully'}), 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
except Exception as e:
|
| 219 |
return jsonify({'error': str(e)}), 500
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
@app.route('/api/health', methods=['GET'])
|
| 222 |
def health():
|
| 223 |
+
return jsonify({
|
| 224 |
+
"status": "healthy",
|
| 225 |
+
"dataset": DATASET_REPO,
|
| 226 |
+
"hf_token_configured": bool(HF_TOKEN)
|
| 227 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
if __name__ == '__main__':
|
| 230 |
port = int(os.environ.get('PORT', 7860))
|
| 231 |
+
app.run(host='0.0.0.0', port=port)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|