<repo_name>Misowii/CIS423<file_sep>/WebServer/python/engine.py
#!/usr/bin/python
from numpy import loadtxt, append, array;
from Predictors import NaiveBayes;
from pickle import load, dump;
from sys import argv;
import os, urllib, json;

os_bracket = '/';

def loadData(datSRC, delim, typ):
	return loadtxt(datSRC, delimiter=delim, dtype = typ);

def googleSearch(search):
	'work around for google search api - i think...'
	query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s";#search api? free to use
	results = urllib.urlopen( query % (search) );
	json_res = json.loads( results.read() );
	return int(json_res['responseData']['cursor']['estimatedResultCount']); #returns number of estimated search results

def loadClassifier(objFile, path = 'training-data'):
	'loads an already saved classifier, path by default os training data directory'
	if os.path.isfile( (path + os_bracket + objFile) ):
		return NaiveBayes( load( open(path + os_bracket + objFile) ) );
	else:
		#print path + os_bracket + objFile;
		print '\n[!NO CLASSIFIFER IS SAVED YET!]\n'
		return None;

def getClassifier(trainDat = 'train-dat.csv', delim = ',', path = 'training-data'):
	'Trains a new classifier, if user does not want ao specific training data, use default'
	data = loadData( (path + os_bracket + trainDat) , delim, float); #load training data
	nv = NaiveBayes();
	nv.summarizeByClass(data); #train classififer
	f = open( (path + os_bracket +'classifier.pickle'), 'wb');
	dump(nv.summaries, f); #save trained classififer as python pickle
	return nv; #return trained classififer

def discretizedFreq(frequency):
	if frequency < 1250: return 1;
	if frequency < 4500: return 2;
	if frequency < 8000: return 3;
	if frequency < 16000: return 4;
	if frequency < 35000: return 5;
	return 6;

def main():
	#argv[1] -> name of file that contains user input (should only contain 3 lines)
	#srcTxt -> input string user needed to translate - 1st line
	#dstTxt -> translated text online app provided - 2nd line
	srcTxt = argv[1];
	dstTxt = argv[2];
	#loadData(argv[1], '\n', str);
	classifier = loadClassifier('classifier.pickle');
	if classifier is None:
		classifier = getClassifier('eng-to-rus.csv');

	frequency = discretizedFreq( googleSearch(dstTxt) );
	textSize = len(srcTxt);

	label, prob = classifier.predict( [textSize, frequency] );
	prediction = ''; prob *= 100; #convert prob into a percentage
	if label == 1: prediction = 'good';
	else: prediction = 'bad';

	#print '\n>> source text: %s ' % srcTxt ;
	#print '>> translated text: %s' % dstTxt;
	print 'Predicted translation type: %s Prediction confidence percentage: %f percent' % prediction, %prob;
	

#if-condition executes main functions when file used directly
if __name__ == '__main__':
	main();

<file_sep>/WebServer/README.md
###Accurp-Engine

About
-----
Collection of machine learning methods to predict a translated text's accuracy.
At the moment the Naive classifier is the onlyone suitable for predicitons. An update to the regression 
predictor is pending, (convert it to a beta-regression-model).


How to Use
----------
Please look at engine.py to see how to use the classifier. 


Testing the Engine
------------------
Pending
<file_sep>/CIS423ChromeExtension/background.js
chrome.browserAction.onClicked.addListener(function(tab){
	var tabURL = "about:black";


	chrome.tabs.query({active: true, lastFocusedWindow: true}, 
			(function(arrayOfTabs){
				var activeTab = arrayOfTabs[0];
				//alert(activeTab.url + " ## ");
				tabURL = activeTab.url;
				//alert(tabURL);

				if (CheckURL(tabURL) == true){
					// alert(tabURL);			//action when button is pushed and user is on google translate
					registerValidityRequest();
				}
				else{
					chrome.tabs.update({url: "https://translate.google.com"});
				}

			}
		)
	);

});

function CheckURL(testURL){
	var tempURL = "https://translate.google.com/";
	for (i = 0; i < tempURL.length; i++){
			if (tempURL[i] != testURL[i]){
				return false;
			}
	}
	return true;
};


function registerValidityRequest(){
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
	  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
	    console.log(response.farewell);
	  });
	});
}<file_sep>/CIS423ChromeExtension/todo.txt
todo:

done: get dom 

register click event on icon

send http

recive and display<file_sep>/CIS423ChromeExtension/app.js

getSource = function(){return $(document.all[0]).find("#source").val()};
getTranslation = function(){
	val = "";
	$(document.all[0]).find("#result_box span").each(function(){
		val += $(this).html() + " ";
	});
	return val;
};

checkLanguage = function(){
	return false;
}


// utility & testing functions
setSource = function(val){
	$(document.all[0]).find("#source").val(val);
}

testFunctions = function(){
	console.log("getSource: ", getSource());
	console.log("getTranslation: ", getTranslation());	
}
// testFunctions();

queryValidator = function(i,o){
	var contentType ="application/x-www-form-urlencoded; charset=utf-8";
 
	if(window.XDomainRequest) //for IE8,IE9
	    contentType = "text/plain";
	 
	$.ajax({
	     url:"https://localhost:3000/results?first=" + getSource() + "&second=" + getTranslation() ,
	     type:"GET",
	     contentType:contentType,    
	     success:function(data)
	     {
	        alert("Data from Server"+JSON.stringify(data));
	     },
	     error:function(jqXHR,textStatus,errorThrown)
	     {
	        alert("BAD!! "+errorThrown);
	     }
    });
}




// alert( queryValidator(getSource(), getTranslation()) );
// 



// addButton(){
// 	button = $("body #gt-lang-submit").html();
// 	("body #gt-lang-submit").insertAfter(button);
// }
// 
// 
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    queryValidator(getSource(), getTranslation());
});
