veltrixcode commited on
Commit
747a3e0
·
verified ·
1 Parent(s): 137570a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +442 -65
app.py CHANGED
@@ -1,74 +1,451 @@
 
 
 
1
  import os
 
 
 
2
  import uuid
3
- from fastapi import FastAPI, UploadFile, File, Request, HTTPException
4
- from fastapi.responses import HTMLResponse
5
- from internetarchive import upload
6
-
7
- IA_ACCESS_KEY = os.getenv("YXzY5OrREXLL6XBh")
8
- IA_SECRET_KEY = os.getenv("m2XnL3X7xCB1pNGE")
9
-
10
- if not IA_ACCESS_KEY or not IA_SECRET_KEY:
11
- raise RuntimeError("Set IA_ACCESS_KEY and IA_SECRET_KEY env variables")
12
-
13
- app = FastAPI(title="Internet Archive Image Upload API")
14
-
15
- # ---------- FRONTEND ----------
16
- @app.get("/", response_class=HTMLResponse)
17
- async def home():
18
- return """
19
- <!DOCTYPE html>
20
- <html>
21
- <head>
22
- <title>IA Image Upload</title>
23
- <style>
24
- body { font-family: Arial; background:#111; color:#fff; text-align:center; padding-top:40px }
25
- input, button { padding:10px; margin:10px }
26
- button { cursor:pointer }
27
- </style>
28
- </head>
29
- <body>
30
- <h2>Upload Image to Internet Archive</h2>
31
- <form action="/upload" method="post" enctype="multipart/form-data">
32
- <input type="file" name="file" accept="image/*" required />
33
- <br/>
34
- <button type="submit">Upload</button>
35
- </form>
36
- </body>
37
- </html>
38
- """
39
-
40
- # ---------- API ----------
41
- @app.post("/upload")
42
- async def upload_image(file: UploadFile = File(...)):
43
- if not file.content_type.startswith("image/"):
44
- raise HTTPException(400, "Only images allowed")
45
-
46
- temp_path = f"/tmp/{uuid.uuid4()}_{file.filename}"
47
- with open(temp_path, "wb") as f:
48
- f.write(await file.read())
49
-
50
- identifier = f"hf-img-{uuid.uuid4()}"
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  try:
53
- upload(
54
- identifier=identifier,
55
- files=temp_path,
56
- access_key=IA_ACCESS_KEY,
57
- secret_key=IA_SECRET_KEY,
58
- metadata={
59
- "mediatype": "image",
60
- "title": file.filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
  )
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
- raise HTTPException(500, str(e))
65
- finally:
66
- os.remove(temp_path)
67
 
68
- url = f"https://archive.org/download/{identifier}/{file.filename}"
 
 
 
69
 
70
- return {
71
- "success": True,
72
- "identifier": identifier,
73
- "url": url
74
- }
 
1
+ from flask import Flask, request, jsonify, render_template_string
2
+ import boto3
3
+ from botocore.client import Config
4
  import os
5
+ from datetime import datetime
6
+ import mimetypes
7
+ from werkzeug.utils import secure_filename
8
  import uuid
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ app = Flask(__name__)
11
+
12
+ # Internet Archive S3 Configuration
13
+ IA_ACCESS_KEY = "YXzY5OrREXLL6XBh"
14
+ IA_SECRET_KEY = "m2XnL3X7xCB1pNGE"
15
+ IA_ENDPOINT = "https://s3.us.archive.org"
16
+ IA_BUCKET = "your-bucket-name" # Replace with your IA bucket name
17
+
18
+ # Initialize S3 client
19
+ s3_client = boto3.client(
20
+ 's3',
21
+ endpoint_url=IA_ENDPOINT,
22
+ aws_access_key_id=IA_ACCESS_KEY,
23
+ aws_secret_access_key=IA_SECRET_KEY,
24
+ config=Config(signature_version='s3v4')
25
+ )
26
+
27
+ ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'}
28
+ MAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB
29
+
30
+ def allowed_file(filename):
31
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
32
+
33
+ HTML_TEMPLATE = """
34
+ <!DOCTYPE html>
35
+ <html lang="en">
36
+ <head>
37
+ <meta charset="UTF-8">
38
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
39
+ <title>Image Upload - Archive.org CDN</title>
40
+ <style>
41
+ * {
42
+ margin: 0;
43
+ padding: 0;
44
+ box-sizing: border-box;
45
+ }
46
+
47
+ body {
48
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
49
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
50
+ min-height: 100vh;
51
+ display: flex;
52
+ justify-content: center;
53
+ align-items: center;
54
+ padding: 20px;
55
+ }
56
+
57
+ .container {
58
+ background: rgba(255, 255, 255, 0.95);
59
+ backdrop-filter: blur(10px);
60
+ border-radius: 24px;
61
+ padding: 40px;
62
+ max-width: 600px;
63
+ width: 100%;
64
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
65
+ }
66
+
67
+ h1 {
68
+ color: #2d3748;
69
+ margin-bottom: 10px;
70
+ font-size: 32px;
71
+ text-align: center;
72
+ }
73
+
74
+ .subtitle {
75
+ color: #718096;
76
+ text-align: center;
77
+ margin-bottom: 30px;
78
+ font-size: 14px;
79
+ }
80
+
81
+ .upload-area {
82
+ border: 3px dashed #cbd5e0;
83
+ border-radius: 16px;
84
+ padding: 60px 20px;
85
+ text-align: center;
86
+ cursor: pointer;
87
+ transition: all 0.3s ease;
88
+ background: #f7fafc;
89
+ margin-bottom: 20px;
90
+ }
91
+
92
+ .upload-area:hover {
93
+ border-color: #667eea;
94
+ background: #edf2f7;
95
+ transform: translateY(-2px);
96
+ }
97
+
98
+ .upload-area.dragover {
99
+ border-color: #667eea;
100
+ background: #e6fffa;
101
+ }
102
+
103
+ .upload-icon {
104
+ font-size: 48px;
105
+ margin-bottom: 16px;
106
+ }
107
+
108
+ .upload-text {
109
+ color: #4a5568;
110
+ font-size: 18px;
111
+ margin-bottom: 8px;
112
+ }
113
+
114
+ .upload-hint {
115
+ color: #a0aec0;
116
+ font-size: 14px;
117
+ }
118
+
119
+ input[type="file"] {
120
+ display: none;
121
+ }
122
+
123
+ .btn {
124
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
125
+ color: white;
126
+ border: none;
127
+ padding: 14px 32px;
128
+ border-radius: 12px;
129
+ font-size: 16px;
130
+ font-weight: 600;
131
+ cursor: pointer;
132
+ width: 100%;
133
+ transition: all 0.3s ease;
134
+ box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
135
+ }
136
+
137
+ .btn:hover {
138
+ transform: translateY(-2px);
139
+ box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
140
+ }
141
+
142
+ .btn:disabled {
143
+ background: #cbd5e0;
144
+ cursor: not-allowed;
145
+ box-shadow: none;
146
+ }
147
+
148
+ .preview-container {
149
+ margin: 20px 0;
150
+ display: none;
151
+ }
152
+
153
+ .preview-image {
154
+ max-width: 100%;
155
+ border-radius: 12px;
156
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
157
+ }
158
+
159
+ .result-container {
160
+ margin-top: 20px;
161
+ padding: 20px;
162
+ background: #f0fff4;
163
+ border-radius: 12px;
164
+ border: 2px solid #9ae6b4;
165
+ display: none;
166
+ }
167
+
168
+ .result-container.error {
169
+ background: #fff5f5;
170
+ border-color: #fc8181;
171
+ }
172
+
173
+ .url-box {
174
+ display: flex;
175
+ gap: 10px;
176
+ margin-top: 10px;
177
+ }
178
+
179
+ .url-input {
180
+ flex: 1;
181
+ padding: 12px;
182
+ border: 2px solid #e2e8f0;
183
+ border-radius: 8px;
184
+ font-size: 14px;
185
+ font-family: monospace;
186
+ }
187
+
188
+ .copy-btn {
189
+ padding: 12px 24px;
190
+ background: #667eea;
191
+ color: white;
192
+ border: none;
193
+ border-radius: 8px;
194
+ cursor: pointer;
195
+ font-weight: 600;
196
+ transition: all 0.3s ease;
197
+ }
198
+
199
+ .copy-btn:hover {
200
+ background: #5568d3;
201
+ }
202
+
203
+ .loading {
204
+ display: none;
205
+ text-align: center;
206
+ margin: 20px 0;
207
+ }
208
+
209
+ .spinner {
210
+ border: 4px solid #f3f4f6;
211
+ border-top: 4px solid #667eea;
212
+ border-radius: 50%;
213
+ width: 40px;
214
+ height: 40px;
215
+ animation: spin 1s linear infinite;
216
+ margin: 0 auto;
217
+ }
218
+
219
+ @keyframes spin {
220
+ 0% { transform: rotate(0deg); }
221
+ 100% { transform: rotate(360deg); }
222
+ }
223
+
224
+ .file-info {
225
+ margin: 15px 0;
226
+ padding: 12px;
227
+ background: #edf2f7;
228
+ border-radius: 8px;
229
+ display: none;
230
+ }
231
+
232
+ .file-info-text {
233
+ color: #4a5568;
234
+ font-size: 14px;
235
+ }
236
+ </style>
237
+ </head>
238
+ <body>
239
+ <div class="container">
240
+ <h1>📸 Image Upload</h1>
241
+ <p class="subtitle">Upload to Archive.org CDN</p>
242
+
243
+ <div class="upload-area" id="uploadArea">
244
+ <div class="upload-icon">☁️</div>
245
+ <div class="upload-text">Click or drag image here</div>
246
+ <div class="upload-hint">PNG, JPG, GIF, WEBP up to 50MB</div>
247
+ <input type="file" id="fileInput" accept="image/*">
248
+ </div>
249
+
250
+ <div class="file-info" id="fileInfo">
251
+ <div class="file-info-text" id="fileInfoText"></div>
252
+ </div>
253
+
254
+ <div class="preview-container" id="previewContainer">
255
+ <img id="previewImage" class="preview-image" alt="Preview">
256
+ </div>
257
+
258
+ <button class="btn" id="uploadBtn" disabled>Upload Image</button>
259
+
260
+ <div class="loading" id="loading">
261
+ <div class="spinner"></div>
262
+ <p style="margin-top: 10px; color: #4a5568;">Uploading...</p>
263
+ </div>
264
+
265
+ <div class="result-container" id="resultContainer">
266
+ <div style="font-weight: 600; margin-bottom: 10px; color: #2d3748;" id="resultTitle">✅ Upload Successful!</div>
267
+ <div class="url-box">
268
+ <input type="text" class="url-input" id="urlInput" readonly>
269
+ <button class="copy-btn" id="copyBtn">Copy</button>
270
+ </div>
271
+ </div>
272
+ </div>
273
+
274
+ <script>
275
+ const uploadArea = document.getElementById('uploadArea');
276
+ const fileInput = document.getElementById('fileInput');
277
+ const uploadBtn = document.getElementById('uploadBtn');
278
+ const previewContainer = document.getElementById('previewContainer');
279
+ const previewImage = document.getElementById('previewImage');
280
+ const loading = document.getElementById('loading');
281
+ const resultContainer = document.getElementById('resultContainer');
282
+ const urlInput = document.getElementById('urlInput');
283
+ const copyBtn = document.getElementById('copyBtn');
284
+ const fileInfo = document.getElementById('fileInfo');
285
+ const fileInfoText = document.getElementById('fileInfoText');
286
+ const resultTitle = document.getElementById('resultTitle');
287
+
288
+ let selectedFile = null;
289
+
290
+ uploadArea.addEventListener('click', () => fileInput.click());
291
+
292
+ uploadArea.addEventListener('dragover', (e) => {
293
+ e.preventDefault();
294
+ uploadArea.classList.add('dragover');
295
+ });
296
+
297
+ uploadArea.addEventListener('dragleave', () => {
298
+ uploadArea.classList.remove('dragover');
299
+ });
300
+
301
+ uploadArea.addEventListener('drop', (e) => {
302
+ e.preventDefault();
303
+ uploadArea.classList.remove('dragover');
304
+ const files = e.dataTransfer.files;
305
+ if (files.length > 0) {
306
+ handleFile(files[0]);
307
+ }
308
+ });
309
+
310
+ fileInput.addEventListener('change', (e) => {
311
+ if (e.target.files.length > 0) {
312
+ handleFile(e.target.files[0]);
313
+ }
314
+ });
315
+
316
+ function handleFile(file) {
317
+ if (!file.type.startsWith('image/')) {
318
+ alert('Please select an image file');
319
+ return;
320
+ }
321
+
322
+ if (file.size > 50 * 1024 * 1024) {
323
+ alert('File size must be less than 50MB');
324
+ return;
325
+ }
326
+
327
+ selectedFile = file;
328
+
329
+ const reader = new FileReader();
330
+ reader.onload = (e) => {
331
+ previewImage.src = e.target.result;
332
+ previewContainer.style.display = 'block';
333
+ };
334
+ reader.readAsDataURL(file);
335
+
336
+ fileInfoText.textContent = `${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;
337
+ fileInfo.style.display = 'block';
338
+ uploadBtn.disabled = false;
339
+ resultContainer.style.display = 'none';
340
+ }
341
+
342
+ uploadBtn.addEventListener('click', async () => {
343
+ if (!selectedFile) return;
344
+
345
+ const formData = new FormData();
346
+ formData.append('file', selectedFile);
347
+
348
+ uploadBtn.disabled = true;
349
+ loading.style.display = 'block';
350
+ resultContainer.style.display = 'none';
351
+
352
+ try {
353
+ const response = await fetch('/upload', {
354
+ method: 'POST',
355
+ body: formData
356
+ });
357
+
358
+ const data = await response.json();
359
+
360
+ if (data.success) {
361
+ urlInput.value = data.url;
362
+ resultContainer.className = 'result-container';
363
+ resultTitle.textContent = '✅ Upload Successful!';
364
+ resultContainer.style.display = 'block';
365
+ } else {
366
+ resultContainer.className = 'result-container error';
367
+ resultTitle.textContent = '❌ Upload Failed';
368
+ urlInput.value = data.error || 'Unknown error occurred';
369
+ resultContainer.style.display = 'block';
370
+ }
371
+ } catch (error) {
372
+ resultContainer.className = 'result-container error';
373
+ resultTitle.textContent = '❌ Upload Failed';
374
+ urlInput.value = error.message;
375
+ resultContainer.style.display = 'block';
376
+ } finally {
377
+ loading.style.display = 'none';
378
+ uploadBtn.disabled = false;
379
+ }
380
+ });
381
+
382
+ copyBtn.addEventListener('click', () => {
383
+ urlInput.select();
384
+ document.execCommand('copy');
385
+ copyBtn.textContent = 'Copied!';
386
+ setTimeout(() => {
387
+ copyBtn.textContent = 'Copy';
388
+ }, 2000);
389
+ });
390
+ </script>
391
+ </body>
392
+ </html>
393
+ """
394
+
395
+ @app.route('/')
396
+ def index():
397
+ return render_template_string(HTML_TEMPLATE)
398
+
399
+ @app.route('/upload', methods=['POST'])
400
+ def upload_file():
401
  try:
402
+ if 'file' not in request.files:
403
+ return jsonify({'success': False, 'error': 'No file provided'}), 400
404
+
405
+ file = request.files['file']
406
+
407
+ if file.filename == '':
408
+ return jsonify({'success': False, 'error': 'No file selected'}), 400
409
+
410
+ if not allowed_file(file.filename):
411
+ return jsonify({'success': False, 'error': 'Invalid file type'}), 400
412
+
413
+ # Generate unique filename
414
+ original_filename = secure_filename(file.filename)
415
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
416
+ unique_id = str(uuid.uuid4())[:8]
417
+ filename = f"{timestamp}_{unique_id}_{original_filename}"
418
+
419
+ # Determine content type
420
+ content_type = mimetypes.guess_type(original_filename)[0] or 'application/octet-stream'
421
+
422
+ # Upload to Internet Archive S3
423
+ s3_client.upload_fileobj(
424
+ file,
425
+ IA_BUCKET,
426
+ filename,
427
+ ExtraArgs={
428
+ 'ContentType': content_type,
429
+ 'ACL': 'public-read'
430
  }
431
  )
432
+
433
+ # Generate public URL
434
+ file_url = f"https://archive.org/download/{IA_BUCKET}/{filename}"
435
+
436
+ return jsonify({
437
+ 'success': True,
438
+ 'url': file_url,
439
+ 'filename': filename
440
+ })
441
+
442
  except Exception as e:
443
+ return jsonify({'success': False, 'error': str(e)}), 500
 
 
444
 
445
+ @app.route('/api/upload', methods=['POST'])
446
+ def api_upload():
447
+ """API endpoint for programmatic uploads"""
448
+ return upload_file()
449
 
450
+ if __name__ == '__main__':
451
+ app.run(host='0.0.0.0', port=7860, debug=False)