#!/usr/bin/perl -w

# Aufruf: rte2weka.pl RTE.xml >AUSGABE
# ------------------------------------
# Erzeugt aus einem RTE-Datenset (XML) eine Eingabedatei fuer Weka.
# Peter Kolb, 21.1.2009

# Stoppwortliste einlesen
open(STP, "<stop_words.txt") or die "Nix stop_words.txt!\n";
while(<STP>){
    @zeile = split;
    $STOP{$zeile[0]} = 1;
}
close(STP);

# Kopf der .arff-Datei ausgeben
print STDOUT "\@relation RTE2-TEST_SHALLOW_PK\n\n";
print STDOUT "\@attribute 4goverlap real\n";
print STDOUT "\@attribute textlength integer\n";
print STDOUT "\@attribute hypothesislength integer\n";
print STDOUT "\@attribute task {IE,IR,QA,SUM}\n";
print STDOUT "\@attribute entailment {YES,NO}\n\n";
print STDOUT "\@data\n";

# RTE-XML-Datei durchlaufen
open(EIN, "<$ARGV[0]") or die "Nix $ARGV[0]!\n";
while(<EIN>){
    # T-H-Paare aus RTE-XML-Datei einlesen
    if( /<pair id=\"(.+?)\" entailment=\"(.+?)\" task=\"(.+?)\">/ ){
	$id = $1;
	$entails = $2;
	$task = $3;
	$pair = "";
	do{
	    $_ = <EIN>;
	    chomp;
	    $pair = $pair . $_;
	}while( $_ !~ /<\/pair>/ );
	# Text extrahieren
	if( $pair =~ /<t>(.+?)<\/t>/ ){
	    $text = $1;
	}else{
	    print STDERR "FEHLER in Entailment-Paar Nr. $id: Kein Text!\n";
	}
	# Hypothese extrahieren
	if( $pair =~ /<h>(.+?)<\/h>/ ){
	    $hypothese = $1;
	}else{
	    print STDERR "FEHLER in Entailment-Paar Nr. $id: Keine Hypothese!\n";
	}
	# Laenge (Zeichen) von Text und Hypothese bestimmen
	$text_length = length($text);
	$hypothese_length = length($hypothese);
	# Text und Hypothese tokenisieren und normalisieren
	$text = lc($text);
	$hypothese = lc($hypothese);
	@text = split(/[ \s\t\f\r\n\.:,;!\"\%\$\&\(\)\?\-]+/, $text);
	@hypothese = split(/[ \s\t\f\r\n\.:,;!\"\%\$\&\(\)\?\-]+/, $hypothese);
	# Stoppwoerter herausfiltern
	@text2 = ();
	foreach $token ( @text ){
	    if( !exists($STOP{$token}) ){
		push(@text2, $token);
	    }
	}
	@hypothese2 = ();
	foreach $token ( @hypothese ){
	    if( !exists($STOP{$token}) ){
		push(@hypothese2, $token);
	    }
	}
	# 4-Gramme bestimmen
	%TEXT4G = ();
	%HYPOTHESE4G = ();
	foreach $token ( @text2 ){
	    $token = "___" . $token . "___";
	    for($i = 0; $i <= length($token)-4; $i++ ){
		$TEXT4G{substr($token, $i, 4)}++;
	    }
	}
	foreach $token ( @hypothese2 ){
	    $token = "___" . $token . "___";
	    for($i = 0; $i <= length($token)-4; $i++ ){
		$HYPOTHESE4G{substr($token, $i, 4)}++;
	    }
	}
	# Overlap berechnen
	$z = 0; $n = 0;
	foreach $ngramm ( keys %HYPOTHESE4G ){
	    if( exists($TEXT4G{$ngramm}) ){
		if( $TEXT4G{$ngramm} < $HYPOTHESE4G{$ngramm} ){
		    $z = $z + $TEXT4G{$ngramm};
		}else{
		    $z = $z + $HYPOTHESE4G{$ngramm};
		}
	    }
	    $n = $n + $HYPOTHESE4G{$ngramm};
	}
	$overlap = $z / $n;
	# Merkmale ausgeben
	print STDOUT "$overlap,$text_length,$hypothese_length,$task,$entails\n";
    }
}
close(EIN);


