working on GF integration (iv)

parent ee7b23b5
package com.yottacode.pictogram.grammar;
import android.util.Log;
import com.yottacode.pictogram.dao.Picto;
import com.yottacode.pictogram.tools.PCBcontext;
import org.grammaticalframework.pgf.Concr;
import org.grammaticalframework.pgf.PGF;
import org.grammaticalframework.pgf.ParseError;
import org.grammaticalframework.pgf.TokenProb;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Vector;
/**
* Created by Fernando on 01/06/2016.
*/
public class SemanticGrammar {
private PGF pgf;
Concr language;
String current_msg;
Hashtable<String,Integer> exp_cat; //for a given expression, which is the category. It's required for predictive grammar
public SemanticGrammar(String grammar, String language) {
System.loadLibrary("jpgf");
this.exp_cat = new Hashtable<>(Vocabulary.DEFAULT_VOCABULARY_SIZE);
try {
InputStream in = null;
in = PCBcontext.getContext().getAssets().open(grammar);
Log.i(this.getClass().getCanonicalName(), "Trying to open " + grammar);
this.language = this.pgf.getLanguages().get(language);
this.pgf = PGF.readPGF(in);
this.current_msg="";
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* It adds a new expresion with a given cat
*/
public void add_translation(String translation, int cat) {
this.exp_cat.put(translation,cat);
}
/**
* It returns the category for a given expression. It is required to implement the semantic grammar
* @param translation
* @return
*/
public int get_expr_cat(String translation) {
return this.exp_cat.get(translation);
}
public LinkedList<Picto> startSentence() {
this.current_msg="";
return PCBcontext.getVocabulary().pictos.get(Picto.NO_CATEGORY);
}
public LinkedList<Picto> next_categories(String expression) {
LinkedList<Picto> next_cats;
this.current_msg += expression + " ";
try {
Iterable<TokenProb> next_tokens = language.complete(pgf.getStartCat(), this.current_msg, "");
if (!next_tokens.iterator().hasNext())
next_cats = startSentence();
else {
next_cats = new LinkedList<>();
java.util.LinkedList<Picto> categories = PCBcontext.getVocabulary().pictos.get(Picto.NO_CATEGORY);
for (TokenProb tk : next_tokens) {
String translation = tk.getToken();
int cat = get_expr_cat(tk.getToken());
Log.i(this.getClass().getSimpleName(), "Next: " + translation + ". Cat: " + cat);
if (!next_cats.contains(cat)) {
next_cats.add(categories.get(cat));
}
}
}
} catch (ParseError parseError) {
Log.e(this.getClass().getCanonicalName(), "Error parsing " + this.current_msg + ". Error:" + parseError.getMessage() + " (token " + parseError.getToken() + ")");
next_cats = startSentence();
}
return next_cats;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment