#!/usr/bin/env ruby
# warai.rb $Revision: 1 $
# Copyright (C) 2007  Michitaka Ohno <elpeo@mars.dti.ne.jp>
# You can redistribute it and/or modify it under GPL2.
BEGIN{ $stdout.binmode }

require 'cgi'
require 'uri'
require 'tempfile'
require 'digest/md5'
require 'open-uri'
require 'GD'
require 'detector'

@model = 'haarcascade_frontalface_alt2.xml'
@image = 'warai.png'

cgi = CGI.new
img = cgi.params['img'][0] if cgi.include?( 'img' )
page = cgi.params['page'][0] if cgi.include?( 'page' )

if %r|^http://| =~ img then
	warai = GD::Image.new_from_png( @image )
	tmp = Tempfile.new( Digest::MD5.hexdigest( img ) )
	tmp.print open( img ){|f| f.read}
	tmp.flush
	ary = Detector::detect( @model, tmp.path )
	dst = GD::Image.new_from_jpeg( tmp.path )
	tmp.close
	ary.each do |x, y, w, h|
		dw = w < h ? ( h * warai.width / warai.height): w
		dh = w < h ? h : (w * warai.height / warai.width)
		warai.copyResampled( dst, x+w/2-dw/2, y+h/2-dh/2, 0, 0, dw, dh, warai.width, warai.height )
	end
	print cgi.header( 'type' => 'image/jpeg' )
	print dst.jpegStr( 75 )
elsif %r|^http://| =~ page then
	s = open( page ){|f| f.read}
	s.gsub!( /(img[^<>]+src=")(.+?)(")/im ) do
		uri = URI.join( page, $2 ).to_s
		r1 = "#{$1}#{uri}#{$3}"
		r2 = "#{$1}./warai.rb?img=#{CGI::escape( uri )}#{$3}"
		/\.(gif|png)$/ =~ $2 ? r1 : r2
	end
	print cgi.header( 'type' => 'text/html', 'charset' => "" )
	print s
else
	print cgi.header( 'status' => 'NOT_FOUND' )
end
exit

