Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.23 KB | None | 0 0
  1. public class Main extends javax.swing.JFrame {
  2.  
  3. private static Bot bot;
  4. public BlockingQueue<String> queue;
  5.  
  6. public Main() {
  7. initComponents();
  8.  
  9. //get the parser going
  10. DataParser dp = new DataParser();
  11.  
  12. //make new bot with level 0 as default and given data parser
  13. bot = new Bot("0", dp);
  14.  
  15. //dispaly the default message
  16. txtHistory.setText("Bot: " + bot.getMessage());
  17. }
  18. public Main(BlockingQueue<String>queue) {
  19. this.queue = queue;
  20. }
  21. // display bot response in the text area
  22. private static final String VOICENAME="kevin16";
  23. private static void addBotText(String message) {
  24. txtHistory.setText(txtHistory.getText() + "nBot: " + message);
  25. //turn the bot response to sound
  26. Voice voice;
  27. VoiceManager vm= VoiceManager.getInstance();
  28. voice=vm.getVoice(VOICENAME);
  29.  
  30. voice.allocate();
  31.  
  32. try{
  33. voice.speak(bot.getMessage());
  34. }catch(Exception e){
  35. }
  36. voice.deallocate();
  37. }
  38. public static void listen (String speech) {
  39.  
  40. txtHistory.setText(txtHistory.getText() + "nYou: " + speech + "n");
  41.  
  42. //send the input to the bot and get bot response
  43.  
  44. package bot;
  45.  
  46. import java.io.FileInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.util.ArrayList;
  50. import java.util.HashMap;
  51. import javax.xml.parsers.DocumentBuilder;
  52. import javax.xml.parsers.DocumentBuilderFactory;
  53. import javax.xml.parsers.ParserConfigurationException;
  54. import org.w3c.dom.Document;
  55. import org.w3c.dom.Element;
  56. import org.w3c.dom.NodeList;
  57. import org.xml.sax.SAXException;
  58.  
  59. public class DataParser {
  60. private Document dom;
  61. private HashMap<String, State> states = new HashMap<String, State>();
  62. private ArrayList<String> invalidMessages = new ArrayList();
  63. private int invalidMessageIndex = 0;
  64. public int stateCounter = 1000;
  65. public String fileSource;
  66. // default constructor
  67. public DataParser() {
  68. // Load the XML file and parse it
  69. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  70.  
  71. try {
  72.  
  73. //get the filepath of source
  74. String fileSource = Context.getSource();
  75.  
  76. DocumentBuilder db = dbf.newDocumentBuilder();
  77.  
  78. //parse using builder to get DOM representation of the XML file
  79. dom = db.parse(fileSource);
  80.  
  81. // Load configuration and states from the XML file
  82. loadConfiguration();
  83. loadStates();
  84. } catch (ParserConfigurationException pce) {
  85. pce.printStackTrace();
  86. } catch (SAXException se) {
  87. se.printStackTrace();
  88. } catch (IOException ioe) {
  89. ioe.printStackTrace();
  90. }
  91. }
  92.  
  93. // Load states from XML file
  94. private void loadStates() {
  95.  
  96. // get document element object
  97. Element docEle = dom.getDocumentElement();
  98.  
  99. // get all State node names
  100. NodeList nl = docEle.getElementsByTagName("State");
  101.  
  102. // if node is not null and has children
  103. if (nl != null && nl.getLength() > 0) {
  104.  
  105. // loop through all children
  106. for (int i = 0; i < nl.getLength(); i++) {
  107.  
  108. // get state element
  109. Element el = (Element) nl.item(i);
  110.  
  111. // get state id
  112. String id = el.getAttribute("id");
  113.  
  114. // get all state messages
  115. ArrayList messages = new ArrayList();
  116. NodeList messagesNodeList = el.getElementsByTagName("message");
  117.  
  118. // if messages node is not null and has children
  119. if (messagesNodeList != null && messagesNodeList.getLength() > 0) {
  120.  
  121. // loop through all children
  122. for (int j = 0; j < messagesNodeList.getLength(); j++) {
  123.  
  124. // get current message element
  125. Element elmsg = (Element) messagesNodeList.item(j);
  126.  
  127. // append message node value to the messages list
  128. messages.add(elmsg.getFirstChild().getNodeValue());
  129. }
  130. }
  131.  
  132. // get keywords in the current state
  133. ArrayList keywords = getKeywords(el);
  134.  
  135. // construct a new State object
  136. State state = new State(id, messages, keywords);
  137.  
  138. stateCounter ++;
  139.  
  140. // add the state to the states hashmap
  141. states.put(id, state);
  142. }
  143. }
  144. }
  145.  
  146. // get state object by id
  147. public State getState(String id) {
  148. return states.get(id);
  149. }
  150.  
  151. // create a new state
  152. public void addState(State state){
  153. states.put(state.getId(), state);
  154. stateCounter++;
  155. }
  156.  
  157. // get all keywords in an State tag
  158. public ArrayList getKeywords(Element ele) {
  159.  
  160. // construct keywords arraylist
  161. ArrayList keywords = new ArrayList();
  162.  
  163. // get all nodes by keyword tag name
  164. NodeList nl = ele.getElementsByTagName("keyword");
  165.  
  166. // if the tag is not null and has children
  167. if (nl != null && nl.getLength() > 0) {
  168.  
  169. // loop through all the children
  170. for (int i = 0; i < nl.getLength(); i++) {
  171.  
  172. //get the keyword element
  173. Element el = (Element) nl.item(i);
  174.  
  175. // find the keyword target, classname and argument attributes
  176. String wordTag = el.getFirstChild().getNodeValue();
  177. String target = el.getAttribute("target");
  178. String className = el.getAttribute("className");
  179. String arg = el.getAttribute("arg");
  180. String variable = el.getAttribute("variable");
  181. int points = 0;
  182. try{
  183. points = Integer.valueOf(el.getAttribute("points"));
  184. }catch (Exception e){
  185.  
  186. }
  187.  
  188. String learn = el.getAttribute("learn");
  189. // split keyword by comma
  190. String[] words = wordTag.split(",");
  191.  
  192. // loop through all words
  193. for (String word : words) {
  194.  
  195. // trim the word to remove spaces
  196. word = word.trim();
  197.  
  198. // construct a new keyword
  199. Keyword keyword = new Keyword(word, target, className, arg, variable, points, learn );
  200.  
  201. // add the keyword to keywords array list
  202. keywords.add(keyword);
  203. }
  204. }
  205. }
  206.  
  207. // return all the keywords in the given node
  208. return keywords;
  209. }
  210.  
  211.  
  212. // returns one of the invalid messages and move the index to the next message
  213. public String getInvalidAnswer() {
  214.  
  215. // get current answer
  216. String answer = invalidMessages.get(invalidMessageIndex);
  217.  
  218. // increase the index, if it is end of messages, reset the index to 0
  219. invalidMessageIndex++;
  220. if (invalidMessageIndex >= invalidMessages.size()) {
  221. invalidMessageIndex = 0;
  222. }
  223. return answer;
  224. }
  225.  
  226. // load cofig tags from data xml file
  227. private void loadConfiguration() {
  228.  
  229. // get document element
  230. Element docEle = dom.getDocumentElement();
  231.  
  232. // get all node names for invalid messages
  233. NodeList node = docEle.getElementsByTagName("InvalidMessages");
  234.  
  235. // get all message nodes inside invalid messages node
  236. NodeList nl = ((Element) node.item(0)).getElementsByTagName("message");
  237.  
  238. // if node is not null and has children
  239. if (nl != null && nl.getLength() > 0) {
  240.  
  241. // loop through all children
  242. for (int i = 0; i < nl.getLength(); i++) {
  243.  
  244. // get message node
  245. Element el = (Element) nl.item(i);
  246.  
  247. // get message and add it to invalid messages array
  248. String message = el.getFirstChild().getNodeValue();
  249. invalidMessages.add(message);
  250. }
  251. }
  252. }
  253. }
  254.  
  255. package bot;
  256.  
  257.  
  258. import smallTalk.Morning;
  259. import smallTalk.Afternoon;
  260. import smallTalk.Evening;
  261. import smallTalk.Night;
  262. import java.util.ArrayList;
  263. import java.util.HashMap;
  264. import java.util.Map;
  265.  
  266. public class Bot {
  267. // Store all regular expression matches
  268. private HashMap<String,String> dictionary;
  269.  
  270. // Default state to start the bot
  271. String level = "0";
  272. DataParser parser;
  273.  
  274. // default constructor
  275. public Bot(String level, DataParser parser) {
  276. dictionary = new HashMap<String,String>();
  277. this.level = level;
  278. this.parser = parser;
  279. }
  280.  
  281. // get current state message
  282. public String getMessage() {
  283. State state = parser.getState(level);
  284. return replaceMatches(state.getMessage()).trim();
  285. }
  286.  
  287. // send user message to the bot and get the response
  288. public String send(String message) {
  289.  
  290. String response = "";
  291. State state = parser.getState(level);
  292.  
  293. // end of the tree
  294. if (state.getKeywords().isEmpty()) {
  295. this.level = "0";
  296. }
  297.  
  298. // match the keyword with given message
  299. Keyword match = parse(message, state.getKeywords());
  300.  
  301. // if no keyword is matched, display one of the invalid answers
  302. if (match == null) {
  303. response = parser.getInvalidAnswer();
  304. } else {
  305.  
  306. // if match classname is provided, check to get the dynamic response
  307. if (match.className.length() > 0) {
  308.  
  309. // check for Weather dynamic response
  310. if (match.className.equals("Weather")) {
  311. Weather weather = new Weather();
  312. response = weather.getResponse(match.arg);
  313. this.level = "0";
  314. }
  315. // check for News dynamic response
  316. else if (match.className.equals("News")) {
  317. News news = new News();
  318. response = news.getResponse(match.arg);
  319. this.level = "0";
  320. }
  321. else if (match.className.equals("Morning")) {
  322. Morning morning = new Morning();
  323. morning.wakeup();
  324. }
  325. else if (match.className.equals("Afternoon")) {
  326. Afternoon afternoon = new Afternoon();
  327. afternoon.midday();
  328. }
  329. else if (match.className.equals("Evening")) {
  330. Evening evening = new Evening();
  331. evening.dinner();
  332. }
  333. else if (match.className.equals("Night")) {
  334. Night night = new Night();
  335. night.late();
  336. }
  337. // check for Topic dynamic response
  338. else if (match.className.equals("Topic")) {
  339. Topic topic = new Topic();
  340. topic.getTopic(match.arg);
  341. }
  342. } else {
  343.  
  344. // get the new state and return the new message
  345. if (response.length() == 0) {
  346.  
  347. this.level = match.target;
  348. state = parser.getState(level);
  349.  
  350. // if it is end of the tree
  351. if (state.getKeywords().isEmpty()) {
  352. response = this.getMessage();
  353. this.level = "0";
  354.  
  355. }
  356. }
  357. }
  358. }
  359. return response;
  360. }
  361.  
  362. // parse the given text to find best match in the keywords
  363. private Keyword parse(String text, ArrayList<Keyword> keylist) {
  364.  
  365. // set the default match to none
  366. int bestMatch = -1;
  367. Keyword match = null;
  368.  
  369. // loop through keywords
  370. for (int i = 0; i < keylist.size(); i++) {
  371.  
  372. // get number of matches of the keyword with given text
  373. int matches = getMatches(text, keylist.get(i));
  374.  
  375. // if match is better than best match, replace it
  376. if (matches > -1 && matches > bestMatch) {
  377. match = keylist.get(i);
  378. bestMatch = matches;
  379. }
  380. }
  381.  
  382. // add best answers regex variable value into the dictionary for future reference
  383. if (match != null){
  384. if(match.learn.length() > 0 ){
  385.  
  386. // get training data keyword and description
  387. String subject = dictionary.get(match.learn);
  388. String result = match.variableValue;
  389.  
  390.  
  391. // create a new state for new trained data
  392. ArrayList<String> messages = new ArrayList<String>();
  393. messages.add(result);
  394. State myState = new State(String.valueOf(parser.stateCounter),messages,new ArrayList());
  395. parser.addState(myState);
  396.  
  397. // add the new trained keyword
  398. Keyword keyword = new Keyword(subject, myState.getId(), "", "", "", 1, "" );
  399. State state = parser.getState("1");
  400. ArrayList<Keyword> keywords = state.getKeywords();
  401. keywords.add(keyword);
  402.  
  403. }else{
  404. if (match.variableValue.length() > 0){
  405. dictionary.put(match.variable, match.variableValue);
  406. }
  407. }
  408. }
  409. return match;
  410. }
  411.  
  412. // get number of matches of the given keywords in the given list
  413. private int getMatches(String text, Keyword keyword) {
  414.  
  415. // no match by default
  416. int result = -1;
  417.  
  418. // return 0 match when keyword is *
  419. if(keyword.keyword.equals("*")){
  420. return keyword.points;
  421. }
  422.  
  423. // if regex is expected
  424. if(keyword.variable.length() > 0){
  425. String match = Regex.match(keyword.keyword, text);
  426. if(match.length() > 0){
  427. keyword.variableValue = match;
  428. return keyword.points;
  429. }
  430. }
  431.  
  432. String[] words = keyword.keyword.split(" ");
  433.  
  434.  
  435. // loop through list of the keywords
  436. for (String word : words) {
  437.  
  438. // if current keyword is in the text, add points
  439. if (text.toLowerCase().indexOf(word.toLowerCase()) >= 0) {
  440. result = result + keyword.points + 1;
  441. } else {
  442. // return null if one of the keywords does not exists
  443. return -1;
  444. }
  445. }
  446. return result;
  447. }
  448.  
  449.  
  450. // replace given text with variables in the dictionary
  451. public String replaceMatches(String text){
  452.  
  453. // replace variables within dictionary in the text
  454. for (Map.Entry<String, String> entry : dictionary.entrySet()) {
  455. text = text.replaceAll("\["+entry.getKey() + "\]", entry.getValue());
  456. }
  457.  
  458. // remove empty variables tags
  459. return Regex.clear(text);
  460. }
  461. }
  462.  
  463. package bot;
  464.  
  465. public class Context {
  466.  
  467. public static String source = "newcontext.xml";
  468.  
  469. //method to get value of source called in dataParser
  470.  
  471. public static String getSource(){
  472. return source;
  473. }
  474. //get the new topic from Topic Class and prepare to reload DataParser/Bot
  475.  
  476. public static void newSource(String currentTopic){
  477. source = currentTopic;
  478. }
  479. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement