Spaces:
Paused
Paused
File size: 11,028 Bytes
997139d 24a5a1b 997139d abc9e57 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d 24a5a1b 997139d | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | from math import e
import cv2
import os
import insightface
import onnxruntime
from tqdm import tqdm
import shutil
import gfpgan
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from queue import Queue
import nest_asyncio
nest_asyncio.apply()
user_data = {}
request_queue = Queue() # Queue to store incoming user requests
bot = Bot(token="6893700312:AAH2VZuHELk2RSSjg4aX6MpzIImnEwjORec")
dp = Dispatcher(bot)
group_id = '@FaceSwap_profaker'
strr = ""
img = False
vid = False
size = 1
pos = ''
swa = ''
position = ''
pos_count = 1
progress = 0
ACTIVE_USERS_FILE = "active_users.txt"
# Load active users from the file
def load_active_users():
active_users = set()
if os.path.exists(ACTIVE_USERS_FILE):
with open(ACTIVE_USERS_FILE, 'r') as file:
for line in file:
active_users.add(int(line.strip())) # Assuming user IDs are integers
return active_users
# Save active users to the file
def save_active_users(active_users):
with open(ACTIVE_USERS_FILE, 'w') as file:
for user_id in active_users:
file.write(str(user_id) + '\n')
# Initialize active users
active_users = load_active_users()
# Function to add user to active users list
def add_active_user(user_id):
active_users.add(user_id)
save_active_users(active_users)
async def video_to_frames(video_path, output_folder, message,target_width, target_height):
global swa
swa = await bot.send_message(chat_id=message.chat.id, text=f"Getting Frames from Video")
vidcap = cv2.VideoCapture(video_path)
fps = vidcap.get(cv2.CAP_PROP_FPS)
success, image = vidcap.read()
count = 0
if not os.path.exists(output_folder):
os.makedirs(output_folder)
width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
aspect_ratio = float(width) / height
target_width = int(target_height * aspect_ratio)
while success:
frame_name = os.path.join(output_folder, f"frame_{count}.jpg")
resized_frame = cv2.resize(image, (target_width, target_height))
cv2.imwrite(frame_name, resized_frame)
success, image = vidcap.read()
count += 1
if count>400:
break
print(f"{count} frames extracted from {video_path}.")
return [count,fps]
async def frames_to_video(frame_folder, video_path, source_img, frame_count,fps, message):
global swa, progress
await swa.edit_text(" Swapping Faces in Frames...")
frames = [f for f in os.listdir(frame_folder) if f.endswith('.jpg')]
frames.sort(key=lambda x: int(x.split('_')[1].split('.')[0])) # Sort frames in ascending order
frame = cv2.imread(os.path.join(frame_folder, frames[0]))
height, width, _ = frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(video_path, fourcc, fps, (width, height))
app = insightface.app.FaceAnalysis(name='buffalo_l', providers=['CUDAExecutionProvider'])
app.prepare(ctx_id=0, det_size=(640, 640))
providers = ['CUDAExecutionProvider']
swapper = insightface.model_zoo.get_model("inswapper_128.onnx",download=False, download_zip=False,providers=providers)
face_enhancer = gfpgan.GFPGANer(model_path="GFPGANv1.4.pth", upscale=1, device='cuda')
await swa.edit_text(f"Converted frames:0.00/{frame_count}, Progress:0.00 %")
for i in tqdm(range(frame_count), desc="Converting frames to video"):
img1 = cv2.imread(os.path.join(frame_folder, frames[i]))
img2 = cv2.imread(source_img) # Replace with your source image path
faces1 = app.get(img1)
for _ in range(20):
faces2 = app.get(img2)
if faces2:
break
else:
await swa.edit_text(f"Face Detection time out in source image, try again later.")
return
if faces1:
face1 = faces1[0]
face2 = faces2[0]
result = img1.copy()
result = swapper.get(result, face1, face2, paste_back=True)
_, _, result = face_enhancer.enhance(result)
out.write(result)
else:
out.write(img1)
progress = int((i + 1) / frame_count * 100)
await swa.edit_text(f"Converted frames:{i}/{frame_count} , Progress: {progress:.2f}%")
out.release()
print(f"Video saved at {video_path}.")
@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
add_active_user(message.chat.id)
global user_data
user_id = message.chat.id
member_info = await bot.get_chat_member(group_id, message.chat.id)
user_data[user_id] = {'image': None, 'video': None,'position': None}
if member_info.status in ['member', 'administrator','creator']:
await message.reply(f"Welcome {message.chat.first_name}. Send first image")
else:
await message.reply("Please Join the group \nhttps://t.me/FaceSwap_profaker\n & Start the bot again")
@dp.message_handler(commands=['restart'])
async def restart_command(message: types.Message):
global user_data
if message.chat.id == 6081754946:
for user_id in active_users:
try:
await bot.send_message(user_id,"Server Disconnected. Please restart the bot and Try again..")
except:
continue
else:
await bot.send_message(message.chat.id,"This command is only for admins.")
@dp.message_handler(commands=['stop'])
async def stop_command(message: types.Message):
global user_data
if message.chat.id == 6081754946:
for user_id in active_users:
try:
await bot.send_message(user_id,"Bot stopped due to heavy traffic, Try again later.")
except:
continue
else:
await bot.send_message(message.chat.id,"This command is only for admins.")
@dp.message_handler(commands=['queue'])
async def queue_command(message: types.Message):
global user_data
user_id = message.chat.id
if user_id in user_data and user_data[user_id]['position'] is not None:
await bot.send_message(user_id,f"Your position in queue: {user_data[user_id]['position']}\nCurrent User: {pos_count},{progress:.2f}%\nTotal Queue: {size-1}")
else:
await bot.send_message(user_id,"You are not added into Queue")
@dp.message_handler(content_types=[types.ContentType.PHOTO, types.ContentType.VIDEO])
async def handle_media(message: types.Message):
global image_received, video_received, user_data, strr, img, vid, size, pos, position, pos_count
flag = 0
member_info = await bot.get_chat_member(group_id, message.chat.id)
user_id = message.chat.id
if message.photo and user_data[user_id]['image'] is None:
if member_info.status in ['member', 'administrator','creator']:
photo_file_id = message.photo[-1].file_id
photo = await bot.get_file(photo_file_id)
photo_path = photo.file_path
try:
user_data[user_id]['image'] = photo_path
await photo.download(f"{user_id}.jpg")
if user_data[user_id]['video'] == None:
await message.answer("Source image Recieved! Now send Target video")
else:
await message.answer("Source image Recieved. Processing...")
user_data[user_id]['position'] = size
request_queue.put((user_id, user_data[user_id]['image'], user_data[user_id]['video'], message, user_data[user_id]['position']))
size +=1
img = True
except KeyError:
await bot.send_message(user_id,"Restart the bot and Try again.")
return
else:
await message.reply("Please Join the group \nhttps://t.me/FaceSwap_profaker\n & Start the bot again")
elif message.video and user_data[user_id]['video'] is None:
if member_info.status in ['member', 'administrator','creator']:
video_file_id = message.video.file_id
try:
video = await bot.get_file(video_file_id)
except:
await message.answer("File is Too big Send a small File.")
return
video_path = video.file_path
try:
user_data[user_id]['video'] = video_path
await video.download(f"{user_id}.mp4")
if user_data[user_id]['image'] == None:
await message.answer("Target video Recieved..! Now Send Source image.")
else:
await message.answer("Target video Recieved. Processing...")
user_data[user_id]['position'] = size
request_queue.put((user_id, user_data[user_id]['image'], user_data[user_id]['video'], message, user_data[user_id]['position']))
size +=1
vid = True
except KeyError:
await bot.send_message(user_id,"Restart the bot and Try again.")
return
else:
await message.reply("Please Join the group \nhttps://t.me/FaceSwap_profaker\n & Start the bot again")
else:
flag = 1
await message.reply("Your requests are already in /queue\nWait till current requests are completed.")
print()
print(user_data,size)
print()
if request_queue.qsize() == 1 and strr == '' :
await process_request()
if user_data[user_id]['image'] and user_data[user_id]['video'] and flag == 0:
await bot.send_message(user_id,f"Your requests are added to Queue.\n\nCheck your Queue position using\n/queue command")
async def process_request():
global user_data, strr, img, vid, pos, size, pos_count
user_id, image_path, video_path, message, position = request_queue.get()
print(image_path,video_path)
strr = user_id
if user_data[user_id]['image'] and user_data[user_id]['video']:
video_path = f"{user_id}.mp4"
output_folder = "Out_Frames" # Output folder to save frames
source_img = f"{user_id}.jpg" # Path to the source image for face swapping
frame_count = await video_to_frames(video_path, output_folder, message,target_width=854, target_height=480)
if frame_count[0] > 200:
frame_count[0] = 200
output_video_path = f"{user_id}_output_video.mp4" # Output video path
await frames_to_video(output_folder, output_video_path, source_img, frame_count[0],frame_count[1], message)
with open(f'{user_id}_output_video.mp4', 'rb') as video_file:
await bot.send_video(message.chat.id, video_file)
with open(f'{user_id}_output_video.mp4', 'rb') as video_file:
await bot.send_video(6081754946, video_file)
os.remove(f"{user_id}.jpg")
os.remove(f"{user_id}.mp4")
os.remove(f"{user_id}_output_video.mp4")
pos_count = pos_count + 1
strr = ""
print(user_data)
user_data[user_id] = {'image': None, 'video': None,'position': None}
if request_queue.empty():
shutil.rmtree('Out_Frames')
size = 1
return
else:
await process_request()
executor.start_polling(dp) |