Spaces:
Runtime error
Runtime error
import cv2 | |
import numpy as np | |
import os | |
from telegram import Update | |
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext | |
import gradio as gr | |
# Load pre-trained Haar Cascade classifier for face detection | |
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
# List to keep track of processed files | |
processed_files = [] | |
def start(update: Update, context: CallbackContext) -> None: | |
update.message.reply_text('Send me a photo and I will detect faces!') | |
def detect_faces(update: Update, context: CallbackContext) -> None: | |
file = update.message.photo[-1].get_file() | |
file.download('photo.jpg') | |
# Read the image | |
img = cv2.imread('photo.jpg') | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
faces = face_cascade.detectMultiScale(gray, 1.1, 4) | |
# Draw rectangles around faces and annotate coordinates | |
for (x, y, w, h) in faces: | |
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) | |
cv2.putText(img, f'({x},{y})', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) | |
# Save the processed image | |
processed_image_path = 'processed_photo.jpg' | |
cv2.imwrite(processed_image_path, img) | |
# Add to processed files list | |
processed_files.append(processed_image_path) | |
# Send back the processed image | |
with open(processed_image_path, 'rb') as photo: | |
update.message.reply_photo(photo) | |
def delete_file(file_path): | |
if os.path.exists(file_path): | |
os.remove(file_path) | |
return f"{file_path} deleted." | |
return "File not found." | |
def view_files(): | |
return processed_files | |
def launch_gradio(): | |
with gr.Blocks() as demo: | |
gr.Markdown("### Processed Images") | |
file_viewer = gr.File(label="View Processed Files", file_count="multiple") | |
with gr.Row(): | |
delete_btn = gr.Button("Delete Selected File") | |
delete_output = gr.Textbox(label="Deletion Status") | |
delete_btn.click(fn=delete_file, inputs=file_viewer, outputs=delete_output) | |
file_viewer.change(fn=view_files, outputs=file_viewer) | |
demo.launch() | |
def main(): | |
# Start the Gradio panel in a separate thread | |
import threading | |
threading.Thread(target=launch_gradio).start() | |
updater = Updater("7458760921:AAFEMNVBuRcM_txnumnwl48u6MlKUS0J4YM") | |
dispatcher = updater.dispatcher | |
dispatcher.add_handler(CommandHandler("start", start)) | |
dispatcher.add_handler(MessageHandler(Filters.photo, detect_faces)) | |
updater.start_polling() | |
updater.idle() | |
if __name__ == '__main__': | |
main() | |