Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -623,6 +623,7 @@ def uploaded_file(filename):
|
|
623 |
|
624 |
|
625 |
# 🧠 2. Маршрут: сохраняет файл только в память (BytesIO)
|
|
|
626 |
@app.route('/upload_memory', methods=['POST'])
|
627 |
def upload_file_to_memory():
|
628 |
if 'file' not in request.files:
|
@@ -632,80 +633,45 @@ def upload_file_to_memory():
|
|
632 |
if file.filename == '':
|
633 |
return jsonify({"error": "No selected file"}), 400
|
634 |
|
635 |
-
|
|
|
636 |
return jsonify({"error": "Invalid file type"}), 400
|
637 |
|
|
|
638 |
timestamp = datetime.now().strftime('%Y.%m.%d_%H:%M:%S_')
|
639 |
filename = timestamp + file.filename
|
640 |
|
|
|
641 |
memory_buffer = BytesIO()
|
642 |
try:
|
643 |
-
|
644 |
-
memory_buffer.write(chunk)
|
645 |
-
|
646 |
memory_buffer.seek(0)
|
|
|
|
|
647 |
latest_image["data"] = memory_buffer
|
648 |
latest_image["filename"] = filename
|
649 |
|
650 |
return jsonify({
|
651 |
-
"message": "Image uploaded
|
652 |
"filename": filename
|
653 |
}), 200
|
654 |
|
655 |
except Exception as e:
|
656 |
return jsonify({"error": str(e)}), 500
|
657 |
|
658 |
-
#
|
659 |
-
latest_image = {
|
660 |
-
"data": None,
|
661 |
-
"filename": "",
|
662 |
-
"color_percentages": {"green": 0, "yellow": 0, "brown": 0}
|
663 |
-
}
|
664 |
-
|
665 |
-
def analyze_colors(image_bytes):
|
666 |
-
image_bytes.seek(0)
|
667 |
-
file_bytes = np.asarray(bytearray(image_bytes.read()), dtype=np.uint8)
|
668 |
-
img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
|
669 |
-
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
|
670 |
-
|
671 |
-
# Оптимизированные, но безопасные диапазоны цветов
|
672 |
-
color_ranges = {
|
673 |
-
"green": ((36, 40, 40), (86, 255, 255)), # Зеленый (оставил как было)
|
674 |
-
"yellow": ((22, 100, 100), (32, 255, 255)), # Желтый (немного расширил)
|
675 |
-
"orange": ((10, 120, 120), (20, 255, 255)), # Оранжевый (чуть уменьшил насыщенность)
|
676 |
-
"brown": ((5, 50, 20), (15, 150, 150)) # Коричневый (оставил почти как было)
|
677 |
-
}
|
678 |
-
|
679 |
-
total_pixels = img.shape[0] * img.shape[1]
|
680 |
-
results = {}
|
681 |
-
|
682 |
-
for color, (lower, upper) in color_ranges.items():
|
683 |
-
mask = cv2.inRange(hsv, np.array(lower), np.array(upper))
|
684 |
-
percent = round(cv2.countNonZero(mask) / total_pixels * 100, 1)
|
685 |
-
results[color] = percent
|
686 |
-
|
687 |
-
return results
|
688 |
-
|
689 |
@app.route('/last_image', methods=['GET'])
|
690 |
def get_last_image():
|
691 |
if latest_image["data"] is None:
|
692 |
return jsonify({"error": "No image available"}), 404
|
693 |
|
694 |
-
# Анализ цвета
|
695 |
latest_image["data"].seek(0)
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
return send_file(image_copy, mimetype='image/jpeg', download_name=latest_image["filename"])
|
703 |
-
|
704 |
-
@app.route('/color_stats')
|
705 |
-
def color_stats():
|
706 |
-
stats = latest_image["color_percentages"]
|
707 |
-
print(f"Raw color stats: {stats}") # Для отладки в консоли
|
708 |
-
return jsonify(stats)
|
709 |
|
710 |
|
711 |
@app.route('/view_image', methods=['GET'])
|
|
|
623 |
|
624 |
|
625 |
# 🧠 2. Маршрут: сохраняет файл только в память (BytesIO)
|
626 |
+
# Маршрут для загрузки файла в память
|
627 |
@app.route('/upload_memory', methods=['POST'])
|
628 |
def upload_file_to_memory():
|
629 |
if 'file' not in request.files:
|
|
|
633 |
if file.filename == '':
|
634 |
return jsonify({"error": "No selected file"}), 400
|
635 |
|
636 |
+
# Проверка типа файла (разрешаем только изображения)
|
637 |
+
if not file.filename.lower().endswith(('.jpg', '.jpeg', '.png')):
|
638 |
return jsonify({"error": "Invalid file type"}), 400
|
639 |
|
640 |
+
# Создаем имя файла с timestamp
|
641 |
timestamp = datetime.now().strftime('%Y.%m.%d_%H:%M:%S_')
|
642 |
filename = timestamp + file.filename
|
643 |
|
644 |
+
# Сохраняем в память
|
645 |
memory_buffer = BytesIO()
|
646 |
try:
|
647 |
+
file.save(memory_buffer)
|
|
|
|
|
648 |
memory_buffer.seek(0)
|
649 |
+
|
650 |
+
# Обновляем последнее изображение
|
651 |
latest_image["data"] = memory_buffer
|
652 |
latest_image["filename"] = filename
|
653 |
|
654 |
return jsonify({
|
655 |
+
"message": "Image uploaded successfully",
|
656 |
"filename": filename
|
657 |
}), 200
|
658 |
|
659 |
except Exception as e:
|
660 |
return jsonify({"error": str(e)}), 500
|
661 |
|
662 |
+
# Маршрут для получения последнего изображения
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
663 |
@app.route('/last_image', methods=['GET'])
|
664 |
def get_last_image():
|
665 |
if latest_image["data"] is None:
|
666 |
return jsonify({"error": "No image available"}), 404
|
667 |
|
|
|
668 |
latest_image["data"].seek(0)
|
669 |
+
return send_file(
|
670 |
+
latest_image["data"],
|
671 |
+
mimetype='image/jpeg',
|
672 |
+
download_name=latest_image["filename"]
|
673 |
+
)
|
674 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
675 |
|
676 |
|
677 |
@app.route('/view_image', methods=['GET'])
|