#!/usr/bin/perl

$INFILE = $ARGV[0];
$INLANG = $ARGV[1];

$GCSTMP = 'gs://[YOURBUCKET]/TMP/';
$PROJECTID = '[YOURPROJECTID]';

binmode(STDOUT, ":utf8");

#####################################################################################
#FIRST WRITE THE HTML PROXY FOR GOOGLE TRANSLATE...

open(FILE, $INFILE); binmode(FILE, ":utf8");
open(OUT, ">$INFILE.gtrans_to"); binmode(OUT, ":utf8"); print OUT "<p>";
$LASTLINE = ''; $WRITEID = 0;
while(<FILE>) {
    $_=~s/\s+$//;
    if ($_=~/^(\d+)\s*$/ && $LASTLINE == '') { $SRT_ID = $1; next; };
    if ($_=~/^(\d.*?\-\->.*?\d)$/ && $SRT_ID ne '') { $SRT_TIME = $_; next; };
    if ($_ eq '') {
	$SRT_IDS{$WRITEID} = $SRT_ID; $SRT_TIMES{$WRITEID} = $SRT_TIME;
	print OUT "<s id=$WRITEID>" . $SRT_TXT . "</s> ";
	if ($SRT_TXT=~/[.?!]\s*$/) { print OUT "</p><p>"; };
	$SRT_ID = ''; $SRT_TIME = ''; $SRT_TXT = '';
	$WRITEID++;
    }
    $SRT_TXT .= $_ . ' ';    
}
if ($SRT_TXT ne '') {
    print OUT "<s id=$WRITEID>" . $SRT_TXT . "</s> ";
}
close(FILE);
print OUT "</p>"; close(OUT);
#####################################################################################

#####################################################################################
#NOW SUBMIT TO GCS AND RUN THROUGH GOOGLE TRANSLATE...

#first copy to our temp directory...
system("gsutil cp $INFILE.gtrans_to $GCSTMP/$$/IN/in.html");

#now submit to Google Translate...
$ret = `curl -H "X-Goog-User-Project: $PROJECTID" -X POST -H "Content-Type: application/json; charset=utf-8" -H "Authorization: Bearer \$(gcloud auth print-access-token)" "https://translate.googleapis.com/v3beta1/projects/$PROJECTID/locations/us-central1:batchTranslateText" -d '{
  "sourceLanguageCode": "$INLANG",
  "targetLanguageCodes": ["en"],
  "inputConfigs": { "mimeType": "text/html", "gcsSource": { "inputUri": "$GCSTMP/$$/IN/in.html" } },
  "outputConfig": { "gcsDestination": { "outputUriPrefix": "$GCSTMP/$$/OUT/" } }                   
}'`;
print "RET = $ret\n";

#and get the JOBID...
($JOBID) = $ret=~/"name":\s*"([^"]+)"/;
print "JOBID($JOBID)\n";
if ($JOBID eq '') { print "FATAL: Invalid JobID: Error...\n"; exit; };

#and now loop waiting for the job to complete...
while() {
    print "Waiting 10 Seconds...\n";
    sleep 10;
    print "\tChecking if done...\n";
    $ret = ''; $ret = `curl -s -H "X-Goog-User-Project: $PROJECTID" -X GET -H "Authorization: Bearer \$(gcloud auth application-default print-access-token)" "https://translation.googleapis.com/v3/$JOBID"`;
    if ($ret=~/"state": "FAILED"/) {
    	#clean up and bail...
	print "FATAL: $ret\n";
	system("gsutil rm -r $GCSTMP/$$/*");
	exit;    
    }
    if ($ret=~/"state": "SUCCEEDED"/) {
    	#download locally and clean up GCS...
	print "Translation Completed Successfully...\n";
	system("gsutil cat $GCSTMP/$$/OUT/*.html > $INFILE.gtrans_from");
	system("gsutil rm -r $GCSTMP/$$/*");
	last;    
    }
}

#####################################################################################

#####################################################################################
#AND RECONSTRUCT INTO THE TRANSLATED SRT FILE...

$OUTFILE = $INFILE; $OUTFILE=~s/\.srt/\.translated\.srt/;
open(OUT, ">$OUTFILE"); binmode(OUT, ":utf8");
open(FILE, "$INFILE.gtrans_from"); binmode(FILE, ":utf8"); read(FILE, $buf, (-s FILE)); close(FILE);
while($buf=~/<s id=(\d+)>(.*?)<\/s>/gs) {
    print OUT "$SRT_IDS{$1}\n$SRT_TIMES{$1}\n$2\n\n";
}
close(OUT);

#and clean up...
unlink("$INFILE.gtrans_to");
unlink("$INFILE.gtrans_from");

print "Done...\n\n";
#####################################################################################




