is-a / app.py
Kastg
Update app.py
0006475 verified
raw
history blame
2.01 kB
from flask import Flask, request, jsonify, send_from_directory
import shutil
import os
import requests
app = Flask(__name__)
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=["POST"])
def upload_image():
url = request.form.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
# Determine the file format
if 'jpeg' in content_type:
file_extension = 'jpg'
elif 'png' in content_type:
file_extension = 'png'
else:
return jsonify({"message": "Unsupported image format"}), 400
# Save the image
filename = f"uploaded_image.{file_extension}"
image_path = os.path.join(IMAGE_FOLDER, filename)
with open(image_path, 'wb') as f:
f.write(response.content)
# Update available images dictionary
available_images[filename] = {"url": url, "name": filename}
return jsonify({"message": "File uploaded successfully", "image_url": f"/images/{filename}"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True)