﻿#!/usr/bin/env python
# coding: utf-8

import os
import ffmpeg
import re

def set_title_as_filename(folder_path,file) :
	# 获取文件名
	#filename = os.path.splitext(os.path.basename(file_path)) [0]
	file_path = os.path.join(folder_path, file) 
	new_file_path = os.path.join(folder_path, "new." + file) 
	match = re.search(r'[Ss]\d\d[Ee]\d\d',  file)
	if match:
    		title = match.group(0)
	# 打开媒体文件
	stream = ffmpeg.input(file_path) 
	# 设置标题名
	print("file:" + file)
	print("标题名:" + title)
	stream = ffmpeg.output(stream, new_file_path, vcodec="copy", acodec="copy",metadata = 'title=' + title) 
	ffmpeg.run(stream) 
def main() :
	# 指定目录
	folder_path =  os.environ['MEDIA_PATH']               ##"C:\\Media"
	# 获取目录下的所有文件
	files = os.listdir(folder_path) 
	# 遍历所有文件
	for file in files:
		# 判断是否为媒体文件
		if file.endswith(".mp4") or file.endswith(".avi") or file.endswith(".mkv") :
			# 构建文件路径
			#file_path = os.path.join(folder_path, file) 
			# 设置标题名
			set_title_as_filename(folder_path, file) 

if __name__ == '__main__':
	main() 
