/*
  Sample Java code to show how a literature loader pipeline can run the classifer on papers downloaded from
  a resource such as PubMed. The paper's title and abstract should be saved to a file, and passed to the
  python driver script. The path to the classifer .pkl file must also be provided.
  
   See the comment section in text_topic-classifier.py to see how a classifier can be generated ad saved to a file.
  
   The runClassifer() method can be invoked on as many papers as needed, possibly from a loop.
   
   Written by Kamran Karimi
*/
  
import java.io.BufferedReader;
import java.io.InputStreamReader;


public class LiteratureLoader {

    public static void main(String[] args) {
		// Sample hardcoded values
		String fileName = "training-relevant-papers/PMID-19046.txt";
		String classifier = "classifiers/Bagging.pkl"; // Assumes a classifier named Bagging.pkl is already generated in a foldr called classifiers
		
		int paperClass = runClassifier(fileName, classifier);
		if (paperClass == -1) {
			System.out.println("Failed to run the classifier");
		}
		else {
			System.out.println("classifier returned: " + paperClass);
		}
    }


	public static int runClassifier(String fileName, String classifier) {
	
		String line;
		int cls = -1; // default return value (failed)
		String classifierScript = "single_classify.py";
		
		String[] params = {"python3", classifierScript, "-input", fileName, "-clf", classifier};
		try {
			// call the python driver script
			Process clf = Runtime.getRuntime().exec(params);
			
			// capture the script's output
			BufferedReader inputStream = new BufferedReader(new InputStreamReader(clf.getInputStream()));
			BufferedReader stdError = new BufferedReader(new InputStreamReader(clf.getErrorStream()));
			
			while ((line = inputStream.readLine()) != null) {
				System.out.println(line);
			}
			while ((line = stdError.readLine()) != null) {
				System.out.println(line);
			}
			// wait for the python script to finish
			clf.waitFor();
			// get the return value (class; 0 = irrelevant, 1 = relevant)
			cls = clf.exitValue();
		}
		catch (Exception e) {
			e.printStackTrace(System.out);
		}
		return cls;
	}

}
