# -*- coding: utf-8 -*-
import os
import sys
from PIL import Image

config = {
	"width": 216, #转换后的GIF宽度
	"height": 121, #转换后的GIF高度
	"frame": 10, #转换后的GIF帧率
	"zoom": 1, #字符画相对于GIF的缩放倍数
}
Style = '''
<style>
pre { font-size:10px; line-height:4px;}
</style>
''' #HTML页面显示风格
JavaScript = '''
<script>
	var count = -10;
	var Main = '';
	var left = '';
	function Show() {
		if (count < 0) {
			count++;
			return;
		}
		if (count == 0) {
			count++;
			Main = document.getElementsByTagName('body')[0];
			left = Main.firstElementChild;
			left.style.display = 'block';
			return;
		}
		count++;
		text = left.nextElementSibling;
		if (text == false) {
			return;
		}
		Main.removeChild(left);
		left = text;
		left.style.display = 'block';
	}
	setInterval("Show()", 1000/%d);
</script>
''' % config['frame'] #实现切换帧的JS语句
path = sys.path[0] #获取当前路径，打包为EXE时需使用os.getcwd()
color = '@#MBHA&XG893S5h1sri;:-,. ' #字符画的字符集
VideoName = raw_input('Please enter a video name:')
RealName = VideoName.split('.')[0]

def VideoToGIF(): #将视频文件转换为GIF
	os.system('%s/ffmpeg -i %s/%s -s %d*%d -r %d %s/%s.gif'
	%(path, path, VideoName, config['width'], config['height'], config['frame'], path, RealName))

def ImageToText(im): #将图片转换为字符画
	w, h = im.size
	x = config['zoom']
	h /= x
	w /= x
	image = im.convert('L').resize((w, h))
	pix = image.load()
	pic_str = ''

	for i in range(h):
		for j in range(w):
			if int(pix[j, i] * 25 / 255) <= 25:
				pic_str += color[int(pix[j, i] * 25 / 255)]
		pic_str += '\r\n'
	return '<pre style="display: none;">' + pic_str + '</pre>'

def SplitGIF(): #将GIF逐帧分割处理
	im = Image.open('%s/%s.gif' % (path, RealName))
	im.seek(1)
	Pre = ''
	count = 0

	try:
		while True:
			Pre += ImageToText(im)
			if count % (config['frame'] * 10) == 0:
				print '%d S' % (count / config['frame'])
			count += 1
			im.seek(im.tell() + 1)

	except EOFError:
		File = open('%s/%s.html' % (path, RealName), 'w')
		File.write('''
<html>
<head>
%s
%s
</head>
<body>
%s
</body>
</html>
''' % (JavaScript, Style, Pre))
		File.close()
		print 'Success!!'

def main():
	VideoToGIF()
	SplitGIF()

if __name__ == '__main__':
	main()