portalniy-dev commited on
Commit
a4c0bc2
·
verified ·
1 Parent(s): 55ac443

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -67
app.py CHANGED
@@ -1,79 +1,83 @@
1
- import os
2
  import cv2
3
  import numpy as np
4
- from PIL import Image, ImageDraw
5
- import telebot
 
6
  import gradio as gr
7
 
8
- # Телеграм-токен
9
- API_TOKEN = '7458760921:AAFEMNVBuRcM_txnumnwl48u6MlKUS0J4YM'
10
- bot = telebot.TeleBot(API_TOKEN)
 
 
11
 
12
- # Создание папок для хранения файлов
13
- os.makedirs('uploads', exist_ok=True)
14
- os.makedirs('processed', exist_ok=True)
15
 
16
- # Загрузка классификатора для распознавания лиц
17
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
 
18
 
19
- # Функция для обработки изображения
20
- def process_image(image_path):
21
- img = cv2.imread(image_path)
22
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
23
- faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
24
-
25
- pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
26
- draw = ImageDraw.Draw(pil_img)
27
-
28
- coords = []
29
  for (x, y, w, h) in faces:
30
- draw.rectangle([x, y, x + w, y + h], outline="green", width=2)
31
- coords.append((x, y, w, h))
32
- draw.text((x, y - 10), f"({x}, {y})", fill="green")
33
-
34
- processed_path = image_path.replace('uploads', 'processed')
35
- pil_img.save(processed_path)
36
- return processed_path, coords
37
-
38
- # Обработчик сообщений с изображениями
39
- @bot.message_handler(content_types=['photo'])
40
- def handle_photo(message):
41
- file_info = bot.get_file(message.photo[-1].file_id)
42
- downloaded_file = bot.download_file(file_info.file_path)
43
-
44
- file_name = f"uploads/{message.photo[-1].file_id}.jpg"
45
- with open(file_name, 'wb') as f:
46
- f.write(downloaded_file)
47
-
48
- processed_path, coords = process_image(file_name)
49
-
50
- # Отправка обработанного изображения с координатами
51
- with open(processed_path, 'rb') as f:
52
- bot.send_photo(message.chat.id, f, caption=f"Координаты лиц: {coords}")
53
-
54
- # Gradio интерфейс
55
- def view_files():
56
- files = os.listdir('processed')
57
- return {file: f"processed/{file}" for file in files}
58
 
59
- def delete_file(file_name):
60
- file_path = f"processed/{file_name}"
 
 
 
61
  if os.path.exists(file_path):
62
  os.remove(file_path)
63
- return f"Файл {file_name} удалён."
64
- return f"Файл {file_name} не найден."
65
-
66
- with gr.Blocks() as gr_interface:
67
- gr.Markdown("## Управление обработанными изображениями")
68
- with gr.Row():
69
- gallery = gr.Gallery(label="Обработанные файлы").style(grid=3)
70
- with gr.Row():
71
- delete_button = gr.Button("Удалить выбранный файл")
72
- delete_input = gr.Textbox(label="Имя файла для удаления")
73
- delete_output = gr.Textbox(label="Результат удаления")
74
-
75
- delete_button.click(delete_file, inputs=delete_input, outputs=delete_output)
76
- gr.Interface(view_files, [], gallery).launch()
77
-
78
- # Запуск бота
79
- bot.polling()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import cv2
2
  import numpy as np
3
+ import os
4
+ from telegram import Update
5
+ from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
6
  import gradio as gr
7
 
8
+ # Load pre-trained Haar Cascade classifier for face detection
9
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
10
+
11
+ # List to keep track of processed files
12
+ processed_files = []
13
 
14
+ def start(update: Update, context: CallbackContext) -> None:
15
+ update.message.reply_text('Send me a photo and I will detect faces!')
 
16
 
17
+ def detect_faces(update: Update, context: CallbackContext) -> None:
18
+ file = update.message.photo[-1].get_file()
19
+ file.download('photo.jpg')
20
 
21
+ # Read the image
22
+ img = cv2.imread('photo.jpg')
 
23
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
24
+ faces = face_cascade.detectMultiScale(gray, 1.1, 4)
25
+
26
+ # Draw rectangles around faces and annotate coordinates
 
 
 
27
  for (x, y, w, h) in faces:
28
+ cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
29
+ cv2.putText(img, f'({x},{y})', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
30
+
31
+ # Save the processed image
32
+ processed_image_path = 'processed_photo.jpg'
33
+ cv2.imwrite(processed_image_path, img)
34
+
35
+ # Add to processed files list
36
+ processed_files.append(processed_image_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # Send back the processed image
39
+ with open(processed_image_path, 'rb') as photo:
40
+ update.message.reply_photo(photo)
41
+
42
+ def delete_file(file_path):
43
  if os.path.exists(file_path):
44
  os.remove(file_path)
45
+ return f"{file_path} deleted."
46
+ return "File not found."
47
+
48
+ def view_files():
49
+ return processed_files
50
+
51
+ def launch_gradio():
52
+ with gr.Blocks() as demo:
53
+ gr.Markdown("### Processed Images")
54
+
55
+ file_viewer = gr.File(label="View Processed Files", file_count="multiple")
56
+
57
+ with gr.Row():
58
+ delete_btn = gr.Button("Delete Selected File")
59
+ delete_output = gr.Textbox(label="Deletion Status")
60
+
61
+ delete_btn.click(fn=delete_file, inputs=file_viewer, outputs=delete_output)
62
+
63
+ file_viewer.change(fn=view_files, outputs=file_viewer)
64
+
65
+ demo.launch()
66
+
67
+ def main():
68
+ # Start the Gradio panel in a separate thread
69
+ import threading
70
+ threading.Thread(target=launch_gradio).start()
71
+
72
+ updater = Updater("7458760921:AAFEMNVBuRcM_txnumnwl48u6MlKUS0J4YM")
73
+ dispatcher = updater.dispatcher
74
+
75
+ dispatcher.add_handler(CommandHandler("start", start))
76
+ dispatcher.add_handler(MessageHandler(Filters.photo, detect_faces))
77
+
78
+ updater.start_polling()
79
+ updater.idle()
80
+
81
+ if __name__ == '__main__':
82
+ main()
83
+