From a9d3b86008ad0d09f0b6e92638bec94edc2cb6f8 Mon Sep 17 00:00:00 2001
From: Ramin Yaghoubzadeh <ryaghoub@techfak.uni-bielefeld.de>
Date: Mon, 12 Mar 2012 17:28:17 +0100
Subject: [PATCH] We implemented a few steps towards our cool "incremental
 printing demo with feedback"

---
 java/src/ipaacademo/TextPrinter.java | 121 ++++++++++++++++++++-------
 python/test/src/textsender.py        |  95 +++++++++++++++++++++
 python/test/src/wordsender.py        |  48 +++++++++++
 3 files changed, 236 insertions(+), 28 deletions(-)
 create mode 100755 python/test/src/textsender.py
 create mode 100755 python/test/src/wordsender.py

diff --git a/java/src/ipaacademo/TextPrinter.java b/java/src/ipaacademo/TextPrinter.java
index 25f6ce8..88ee186 100644
--- a/java/src/ipaacademo/TextPrinter.java
+++ b/java/src/ipaacademo/TextPrinter.java
@@ -1,13 +1,13 @@
 package ipaacademo;
 
+import java.util.EnumSet;
+import java.util.Map;
+import java.util.HashMap;
 import java.util.Set;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
 
-import ipaaca.AbstractIU;
-import ipaaca.Initializer;
-import ipaaca.InputBuffer;
-import ipaaca.LocalIU;
-import ipaaca.OutputBuffer;
-import ipaaca.RemotePushIU;
+import ipaaca.*;
 
 import javax.swing.JFrame;
 import javax.swing.JLabel;
@@ -16,6 +16,23 @@ import com.google.common.collect.ImmutableSet;
 
 public class TextPrinter
 {
+    
+    private static final class MyEventHandler implements HandlerFunctor
+    {
+        @Override
+        public void handle(AbstractIU iu, IUEventType type, boolean local)
+        {
+            switch(type)
+            {
+            case ADDED:  System.out.println("IU added "+iu.getPayload());  break;
+            case COMMITTED: System.out.println("IU committed");  break;
+            case UPDATED: System.out.println("IU updated "+iu.getPayload()); break;
+            case LINKSUPDATED: System.out.println("IU links updated"); break;
+            }            
+        }
+        
+    }
+    
     static
     {
         Initializer.initializeIpaacaRsb();
@@ -53,16 +70,25 @@ public class TextPrinter
         {
             this.inBuffer = inBuffer;
             this.label = label;
+        
+            EnumSet<IUEventType> types = EnumSet.of(IUEventType.ADDED,IUEventType.COMMITTED,IUEventType.UPDATED,IUEventType.LINKSUPDATED);
+            Set<String> categories = new ImmutableSet.Builder<String>().add(CATEGORY).build();
+            MyEventHandler printingEventHandler;    
+            printingEventHandler = new MyEventHandler();
+            this.inBuffer.registerHandler(new IUEventHandler(printingEventHandler,types,categories));
         }
         
         @Override
         public void run()
         {
             long startTime = System.currentTimeMillis();
+            long nextTime = System.currentTimeMillis();
+            //long lastNewLetterTime = System.currentTimeMillis();
             while(true)
             {
-                double duration = (System.currentTimeMillis()-startTime)/1000d;
-                
+                //double duration = (System.currentTimeMillis()-startTime)/1000d;
+                long currentTime = System.currentTimeMillis();
+
                 RemotePushIU iuFirst = null;
                 for (RemotePushIU iu : inBuffer.getIUs())
                 {
@@ -72,26 +98,64 @@ public class TextPrinter
                         break;
                     }
                 }
-                
-                int numChars = (int)(duration/RATE);
-                
-                AbstractIU iu = iuFirst;
-                String str = "";
-                for(int i=0;i<numChars;i++)
-                {
-                    str += iu.getPayload().get("CONTENT");
-                    Set<String> successor = iu.getLinks("SUCCESSOR");
-                    if(successor!=null && !successor.isEmpty())
-                    {
-                        iu = inBuffer.getIU(successor.iterator().next());
-                    }
-                    else
-                    {
-                        break;
+                if (iuFirst==null) {
+                    startTime = System.currentTimeMillis();
+                    continue;
+                }
+                //int numChars = (int)(duration/RATE);
+
+                if (currentTime >= nextTime) {
+                    AbstractIU iu = iuFirst;
+                    String str = "";
+                    int i = 0;
+                    boolean first_new_element = true;
+                    do {
+                        if (iu.getPayload().get("STATE") != null || first_new_element) {
+                            str += "<font color=\"#000000\">";
+                            str += iu.getPayload().get("CONTENT");
+                            str += "</font>";
+                            if (iu.getPayload().get("STATE") == null) {
+                                iu.getPayload().put("STATE", "REALIZED");
+                                first_new_element = false;
+                                nextTime = currentTime + (int)(1000.0*RATE);
+                            }
+                        } else {
+                            str += "<font color=\"#909090\">";
+                            str += iu.getPayload().get("CONTENT");
+                            str += "</font>";
+                            //lastNewLetterTime = System.currentTimeMillis();
+                        }
+                        Set<String> successor = iu.getLinks("SUCCESSOR");
+                        if(successor!=null && !successor.isEmpty())
+                        {
+                            iu = inBuffer.getIU(successor.iterator().next());
+                        }
+                        i++;
+                    } while(! iu.getLinks("SUCCESSOR").isEmpty());
+                    if (iu.getPayload().get("STATE") != null || first_new_element) {
+                    //if (i<numChars) {
+                        str += "<font color=\"#000000\">";
+                        str += iu.getPayload().get("CONTENT");
+                        str += "</font>";
+                        if (iu.getPayload().get("STATE") == null) {
+                            iu.getPayload().put("STATE", "REALIZED");
+                            first_new_element = false;
+                            nextTime = currentTime + (int)(RATE*1000.0);
+                        }
+                    } else {
+                        str += "<font color=\"#909090\">";
+                        str += iu.getPayload().get("CONTENT");
+                        str += "</font>";
+                        //lastNewLetterTime = System.currentTimeMillis();
                     }
+
+                    str = "<html>"+str+"</html>";
+                    //System.out.println(str);
+                    label.setText(str);
+                } else {
+                    // just wait until we can print some more
                 }
-                label.setText(str);
-                
+
                 try
                 {
                     Thread.sleep(200);
@@ -111,7 +175,7 @@ public class TextPrinter
         
         
         OutputBuffer outBuffer = new OutputBuffer("componentX");
-        String[] inputString = {"h","e","l","l","o"," ","w","o","r","l","d","!"};
+        /*String[] inputString = {"h","e","l","l","o"," ","w","o","r","l","d","!"};
         LocalIU predIU = null;        
         for(String str:inputString)
         {
@@ -125,7 +189,8 @@ public class TextPrinter
                 predIU.setLinks("SUCCESSOR",ImmutableSet.of(localIU.getUid()));
             }
             predIU = localIU;
-        }
+        }*/
+
         tp.start();        
     }
 }
diff --git a/python/test/src/textsender.py b/python/test/src/textsender.py
new file mode 100755
index 0000000..0d80433
--- /dev/null
+++ b/python/test/src/textsender.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python
+
+import sys
+import time
+import unittest
+
+import ipaaca
+
+RECV_CATEGORY = 'WORD'
+SEND_CATEGORY = 'TEXT'
+
+
+class TextSender(object):
+	def __init__(self):
+		self.ob = ipaaca.OutputBuffer('TextSenderOut')
+		self.ob.register_handler(self.outbuffer_handle_iu_event)
+		self.ib = ipaaca.InputBuffer('TextSenderIn', [RECV_CATEGORY])
+		self.ib.register_handler(self.inbuffer_handle_iu_event)
+	
+	def outbuffer_handle_iu_event(self, iu, event_type, local):
+		if event_type == "UPDATED":
+			parent_uids = iu.get_links("GRIN")
+			if len(parent_uids) > 0:
+				parent_uid = list(parent_uids)[0]
+				print "updating parent ..."
+				next_uids = iu.get_links('SUCCESSOR')
+				if len(next_uids) > 0:
+					next_uid = list(next_uids)[0]
+					next_iu = self.ob.iu_store[next_uid]
+					next_letter_grin_links = next_iu.get_links("GRIN")
+					if len(next_letter_grin_links) > 0 and list(next_letter_grin_links)[0] != parent_uid:
+						# the next letter belongs to a new word
+						parent_iu = self.ib.iu_store[parent_uid]
+						parent_iu.payload['STATE'] = 'REALIZED'
+					else:
+						# the next letter belongs to the same word
+						parent_iu = self.ib.iu_store[parent_uid]
+						parent_iu.payload['STATE'] = 'STARTED'
+				else:
+					# there are no more letters, this is the end of the final word
+					parent_iu = self.ib.iu_store[parent_uid]
+					parent_iu.payload['STATE'] = 'REALIZED'
+				print " ... done."
+		else:
+			print('(own IU event '+event_type+' '+str(iu.uid)+')')
+
+	
+	def inbuffer_handle_iu_event(self, iu, event_type, local):
+		if event_type == "ADDED": # and iu.category == RECV_CATEGORY:
+			print("Received new word: "+iu.payload['WORD'])
+			sender.publish_text_to_print(iu.payload['WORD'], parent_iu_uid=iu.uid)
+		elif event_type == "RETRACTED":
+			retracted_uid = iu.uid
+			
+		else:
+			print('(IU event '+event_type+' '+str(iu.uid)+')')
+		pass
+	
+	def find_last_iu(self):
+		for iu in self.ob.iu_store.values():
+			if len(iu.get_links('SUCCESSOR')) == 0:
+				return iu
+		return None
+	
+	def publish_text_to_print(self, text, parent_iu_uid=None):
+		previous_iu = self.find_last_iu()
+		if previous_iu is not None:
+			# insert a blank if we already have words in the buffer
+			iu = ipaaca.IU( SEND_CATEGORY )
+			iu.payload = { 'CONTENT': ' ' }
+			self.ob.add(iu)
+			previous_iu.add_links( 'SUCCESSOR', [iu.uid] )
+			iu.add_links( 'PREDECESSOR', [previous_iu.uid] )
+			if parent_iu_uid is not None: iu.add_links( 'GRIN', [parent_iu_uid] )
+			previous_iu = iu
+		for c in text:
+			iu = ipaaca.IU( SEND_CATEGORY )
+			iu.payload = { 'CONTENT': c }
+			self.ob.add(iu)
+			if previous_iu is not None:
+				previous_iu.add_links( 'SUCCESSOR', [iu.uid] )
+				iu.add_links( 'PREDECESSOR', [previous_iu.uid] )
+				if parent_iu_uid is not None: iu.add_links( 'GRIN', [parent_iu_uid] )
+			if previous_iu is not None: print previous_iu.get_all_links()
+			previous_iu = iu
+
+if __name__ == '__main__':
+	sender = TextSender()
+	time.sleep(1.0)
+	sender.publish_text_to_print('(INIT)')
+	print "Press Ctrl-C to cancel..."
+	while True:
+		time.sleep(0.1)
+	
+
diff --git a/python/test/src/wordsender.py b/python/test/src/wordsender.py
new file mode 100755
index 0000000..e68bb72
--- /dev/null
+++ b/python/test/src/wordsender.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+
+import sys
+import time
+import unittest
+
+import ipaaca
+
+SEND_CATEGORY = 'WORD'
+
+
+class WordSender(object):
+	def __init__(self):
+		self.ob = ipaaca.OutputBuffer('WordSenderOut')
+		self.ob.register_handler(self.outbuffer_handle_iu_event)
+	
+	def outbuffer_handle_iu_event(self, iu, event_type, local):
+		if event_type == "UPDATED":
+			print(iu.payload['WORD']+': '+iu.payload['STATE'])
+		else:
+			print('(own IU event '+event_type+' '+str(iu.uid)+')')
+	
+	def find_last_iu(self):
+		for iu in self.ob.iu_store.values():
+			if len(iu.get_links('SUCCESSOR')) == 0:
+				return iu
+		return None
+	
+	def publish_words(self, words):
+		previous_iu = self.find_last_iu()
+		for word in words:
+			iu = ipaaca.IU( SEND_CATEGORY )
+			iu.payload = { 'WORD': word }
+			self.ob.add(iu)
+			if previous_iu is not None:
+				previous_iu.add_links( 'SUCCESSOR', [iu.uid] )
+				iu.add_links( 'PREDECESSOR', [previous_iu.uid] )
+			previous_iu = iu
+
+if __name__ == '__main__':
+	sender = WordSender()
+	sender.publish_words(['this','is','a','demonstration','of','incremental','generation'])
+	print sender.ob.unique_name
+	print "Press Ctrl-C to cancel..."
+	while True:
+		time.sleep(0.1)
+	
+
-- 
GitLab