Spaces:
Running
Running
File size: 2,128 Bytes
53f7a0c 4a672f4 0006475 ae6d72e 4a672f4 62e7ddb 4a672f4 8ef3879 69e4bde c8d1088 4a672f4 c8d1088 4a672f4 0006475 4a672f4 afa61be 62e7ddb afa61be 4a672f4 0006475 ae6d72e 0006475 ae6d72e 0006475 ae6d72e 4a672f4 0006475 4a672f4 69e4bde 62e7ddb 797f638 f984e57 69e4bde |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
from flask import Flask, request, jsonify, send_from_directory
import os
import requests
from PIL import Image
from io import BytesIO
app = Flask(__name__)
BASE_URL = "https://kastg-cdn.hf.space" # Update this with your actual base URL
IMAGE_FOLDER = "images"
app.config["UPLOAD_FOLDER"] = IMAGE_FOLDER
@app.route("/images/<filename>")
def get_image(filename):
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
# Create folders to store uploaded images
UPLOAD_FOLDER = "uploads"
IMAGE_FOLDER = os.path.join(UPLOAD_FOLDER, "images")
for folder in [UPLOAD_FOLDER, IMAGE_FOLDER]:
os.makedirs(folder, exist_ok=True)
# Create a dictionary to store available images
available_images = {}
@app.route("/upload", methods=["GET"])
def upload_image():
url = request.args.get("url")
if not url:
return jsonify({"message": "URL parameter is missing"}), 400
# Check if the URL is valid and get the image content
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
return jsonify({"message": f"Error fetching image from URL: {str(e)}"}), 400
# Check if the response content is an image
content_type = response.headers.get('content-type')
if 'image' not in content_type:
return jsonify({"message": "The provided URL does not lead to an image"}), 400
# Open the image using PIL
try:
img = Image.open(BytesIO(response.content))
except Exception as e:
return jsonify({"message": f"Error processing image: {str(e)}"}), 400
# Save the image
filename = os.path.basename(url)
image_path = os.path.join(IMAGE_FOLDER, filename)
img.save(image_path)
# Update available images dictionary
available_images[filename] = {"url": url, "name": filename}
# Construct the full image URL including the site name
full_image_url = f"{BASE_URL}/images/{filename}"
return jsonify({"message": "File uploaded successfully", "image_url": full_image_url})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True) |