clone3 commited on
Commit
f548caf
·
verified ·
1 Parent(s): b2329b6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import shutil
4
+ import tempfile
5
+ from datetime import datetime
6
+ from flask import Flask, request, jsonify
7
+ from huggingface_hub import login, HfApi
8
+ from werkzeug.utils import secure_filename
9
+
10
+ app = Flask(__name__)
11
+
12
+ # Load environment variables
13
+ HF_TOKEN = os.getenv("HF_TOKEN")
14
+ REPO_ID = os.getenv("HF_REPO_ID")
15
+
16
+ # Initialize Hugging Face API
17
+ login(token=HF_TOKEN)
18
+ api = HfApi()
19
+
20
+ @app.route('/upload', methods=['POST'])
21
+ def upload_image():
22
+ try:
23
+ # Check if required data is present
24
+ if 'image' not in request.files or 'guid' not in request.form or 'ip' not in request.form:
25
+ return jsonify({"error": "Missing image, guid, or ip"}), 400
26
+
27
+ image = request.files['image']
28
+ guid = secure_filename(request.form['guid']) # Sanitize GUID
29
+ ip = request.form['ip']
30
+
31
+ # Validate image
32
+ if not image or not image.filename:
33
+ return jsonify({"error": "No valid image provided"}), 400
34
+
35
+ # Create temporary directory
36
+ with tempfile.TemporaryDirectory() as temp_dir:
37
+ # Create images folder
38
+ temp_image_dir = os.path.join(temp_dir, "images")
39
+ os.makedirs(temp_image_dir, exist_ok=True)
40
+
41
+ # Save image with guid.jpg extension
42
+ temp_image_path = os.path.join(temp_image_dir, f"{guid}.jpg")
43
+ image.save(temp_image_path)
44
+
45
+ # Create metadata
46
+ path_in_repo = f"data/{guid}.jpg"
47
+ metadata = {
48
+ "file_name": path_in_repo,
49
+ "guid": guid,
50
+ "ip": ip,
51
+ "upload_timestamp": datetime.utcnow().isoformat(),
52
+ }
53
+
54
+ # Write metadata to metadata.jsonl
55
+ metadata_file = os.path.join(temp_dir, "metadata.jsonl")
56
+ with open(metadata_file, "a") as f:
57
+ f.write(json.dumps(metadata) + "\n")
58
+
59
+ # Upload to Hugging Face
60
+ api.upload_folder(
61
+ folder_path=temp_dir,
62
+ path_in_repo="",
63
+ repo_id=REPO_ID,
64
+ repo_type="dataset"
65
+ )
66
+
67
+ return jsonify({"message": "Image and metadata uploaded successfully"}), 200
68
+
69
+ except Exception as e:
70
+ return jsonify({"error": str(e)}), 500
71
+
72
+ if __name__ == '__main__':
73
+ app.run(host='0.0.0.0', port=7860)