Files
ofm/current_GUIcode.py
moonanjum26 188e46804b first commit
2018-08-10 12:01:05 +05:30

745 lines
25 KiB
Python

# 1. Name of the test is always Malaria
# 2. Close button to be checked as abort button
# 3. Exceptions for network connection, camera.
#Things to be worked on:
# 1. On window closed by clicking x at top right corner, the application should terminate
# 2. On abort button Clicked, the C++ API should be killed
# 1. Progressbar speed increased with iterations
# (SOLVED) 5. Setting user defined resolutions for image capture in pylon programs
# (SOLVED) 9. Auto focus code for variance calculation
# (SOLVED)2. Stopping/killing threads on abort
# (SOLVED)8. Adjust time for sending data through FTP that should be by stopping or killing threads while they are sleeping .... (Same as 2)
# (SOLVED)3. Focusing window pulse
# (SOLVED)4. sending data for analysis in progress bar
# (SOLVED)6. On abort, stop progress bar.
# (SOLVED)7. Run focussing only on start up.. Ask jayesh about it..
# (SOLVED)1.Command line executions in os.system for basler camera acquisition
global ip1
global ip2
global ip3
global batches
global numframes
batches=2
numframes=5000
ip1="54.191.132.121"
ip2="54.191.13.206"
ip3="52.38.126.238"
#!/usr/bin/python
import numpy
#import cv2
#from pyfirmata import Arduino, util
from gi.repository import Gtk, GObject
import time
from time import sleep
import os
import threading
import sys
import thread
from time import sleep
global count
global x
from threading import Thread
from locale import gettext as _
import subprocess
import ftplib
from ftplib import FTP
#import gpio
import datetime
#global Thread1
#global Thread2
global Acquire
Acquire = False
global ExitVLCThread
ExitVLCThread = False
global Kill
Kill=False
global SendCellDataThread
SendCellDataThread = False
import Queue
global error1
global error2
global error3
global test
global f
global filename
global compress
global st
error1=0
error2=0
error3=0
q=Queue.Queue(1)
#Create a directory to acquire images.
#os.mkdir('/home/odroid/BloodAnalyser/AcquiredData/PatientInformation')
if os.path.isdir("/home/odroid/BloodAnalyser/AcquiredData/"):
os.system("rm -r /home/odroid/BloodAnalyser/AcquiredData/")
os.mkdir('/home/odroid/BloodAnalyser/AcquiredData/')
os.mkdir('/home/odroid/BloodAnalyser/AcquiredData/PatientInformation')
class patientID(Gtk.Window):
def __init__(self):
self.builder = Gtk.Builder()
global name
global age
#Get objects from patient ID Glade file
self.builder.add_from_file('./patientID.glade')
self.window = self.builder.get_object('entrywindow')
self.nextbutton = self.builder.get_object('button1')
self.okbutton=self.builder.get_object('okbutton')
self.name = self.builder.get_object('name')
self.age = self.builder.get_object('age')
self.entryname=self.builder.get_object('entryname')
self.entryage=self.builder.get_object('entryage')
self.entrypatientID=self.builder.get_object('entrypatientID')
#self.check_editable = Gtk.CheckButton("entryname")
#self.entryname = Gtk.Entry()
self.patientID = self.builder.get_object('patientID')
self.builder.connect_signals(self)
#self.entryname = Gtk.Entry()
#self.entryage = Gtk.Entry()
#self.entrypatientID = Gtk.Entry()
#print(self.entryname.get_text())
print('rashmi')
self.window.show()
def on_okbutton_clicked(self,button):
global name
global age
global patientID
global st
ts=time.time()
#blood=BloodAnalyser()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H_%M_%S')
name=self.entryname.get_text()
age=self.entryage.get_text()
patientID=self.entrypatientID.get_text()
self.window.hide()
#filename=folder.append(st)
#filename=filename.append(".txt")
global test
test="malaria"
global filename
filename=folder+st+".txt"
#return
class splashScreen(Gtk.Window):
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file('./splash.glade')
self.builder.connect_signals(self)
self.window = self.builder.get_object('applicationwindow1')
self.image1=self.builder.get_object("image1")
self.window.show()
#self.done=True
#GObject.timeout_add(5000,)
self.window.show
class AutoFocus(Gtk.Window):
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file('./AutoFocus.glade')
self.builder.connect_signals(self)
self.window = self.builder.get_object('AutoFocus_window')
self.image1=self.builder.get_object("image1")
self.autofocus_pulse=self.builder.get_object("autofocus_pulse")
self.autofocus_start=False
#threading.Thread(target=self.UpdateImages).start()
def pulse_invoke(self):
#self.window.show()
try:
os.system('v4l2-ctl -c exposure_absolute=1')
os.system('mplayer tv:// driver=v4l2:device=/dev/video0')
blood_analyser.vlc_invoke()
#return
except:
error2=True
return error2
def variance(self):
try:
os.chdir('/home/odroid/BloodAnalyser/AutoFocus')
#os.system("make clean")
#os.system("source /opt/pylon4/bin/pylon-setup-env.sh /opt/pylon4")
#os.system("make")
#os.system("chmod 777 autofocus")
#os.system("ls")
#itime=time.time()
board=Arduino('/dev/ttyACM0')
#cap = cv2.VideoCapture(0)
n=1
mylistForward=[]
while(n < 50):
board.digital[5].write(1)
board.digital[6].write(1)
# Capture frame-by-frame
os.system("mplayer tv:// -tv driver=v4l2:device=/dev/video0:fps=20 --frames=2 -vo png")
# Our operations on the frame come here
frame=cv2.imread('/home/odroid/BloodAnalyser/AutoFocus/00000002.png')
#image_file = '/home/rbccps/BloodAnalyser/AutoFocus/focus%d.png'%n
self.window.show()
self.image1.set_from_file('/home/odroid/BloodAnalyser/AutoFocus/00000002.png')
a=numpy.var(frame)
print(a)
mylistForward.append(a)
sleep(0.1)
n=n+1
maxMeasure=max(mylistForward)
maxMeasure = maxMeasure - 40
cMeas=0
n=0
print '**************Motor Moving Backwards*******************'
while(n<50):
print("While loop entered")
if cMeas > maxMeasure:
board.digital[5].write(0)
break
board.digital[5].write(1)
board.digital[6].write(0)
os.system("mplayer tv:// -tv driver=v4l2:device=/dev/video0:fps=20 --frames=2 -vo png")
self.image1.set_from_file('/home/odroid/BloodAnalyser/AutoFocus/00000002.png')
frame1=cv2.imread('/home/odroid/BloodAnalyser/AutoFocus/00000002.png')
cMeas=numpy.var(frame1)
print(cMeas)
n=n+1
sleep(0.1)
board.digital[5].write(0)
#cv2.destroyAllWindows()
#n=cap.release()
self.window.hide()
print(n)
# When everything done, release the capture
print("Capture released")
maxMeasure= max(mylistForward)
blood_analyser.vlc_invoke()
#cv2.destroyAllWindows()
except:
global error1
print("HARDWARE MISSING")
error1=1
return error1
def on_timeout(self, user_data):
if self.activity_mode:
self.autofocus_pulse.pulse()
else:
new_value = self.autofocus_pulse.get_fraction() + 0.01
if new_value > 1:
new_value = 0
self.progressbar.set_fraction(new_value)
# As this is a timeout function, return True so that it
# continues to get called
return True
class quit_window(Gtk.Window):
def __init__(self):
self.builder = Gtk.Builder()
os.chdir('/home/odroid/BloodAnalyser')
self.builder.add_from_file('./quit_window.glade')
self.builder.connect_signals(self)
self.window = self.builder.get_object('quit_window')
self.finishbutton = self.builder.get_object('finishbutton')
self.another_testbutton = self.builder.get_object('another_testbutton')
def show_screen(self):
self.window.show()
def on_finishbutton_activate(self, widget):
os.system('rm ./celldata.zip')
os.system('rm -r ./AcquiredData')
os.system('mkdir ./AcquiredData')
Gtk.main_quit()
def on_another_testbutton_activate(self,widget):
#os.system('rm ./celldata.zip')
#os.system('rm -r ./AcquiredData')
#os.system('mkdir ./AcquiredData')
print "ANother test selected"
self.progressbar.set_fraction(0.0)
self.timeout_id = GObject.timeout_add(False, self.on_timeout,None)
blood_analyser.start.set_label("START TEST")
blood_analyser = BloodAnalyser()
#splScr = splashScreen()
patient_ID=patientID()
Gtk.main()
class BloodAnalyser(Gtk.Window):
def __init__(self):
global count
count=0
global x
x=0
self.builder = Gtk.Builder()
self.builder.add_from_file('./bloodAnalyser.glade')
self.builder.connect_signals(self)
self.window = self.builder.get_object('window1')
self.window.show()
self.infectious_disease = self.builder.get_object("infectious_disease")
self.hamatological_disorder =self.builder.get_object("hematological")
self.completebloodcount = self.builder.get_object("completebloodcount")
self.malaria = self.builder.get_object("malaria")
self.dengue = self.builder.get_object("dengue")
self.tuberculosis = self.builder.get_object("tuberculosis")
self.spherocytosis = self.builder.get_object("spherocytosis")
self.sicklecellanemia=self.builder.get_object("sicklecellanemia")
self.hereditaryelliptocytosis=self.builder.get_object("hereditaryelliptocytosis")
self.start = self.builder.get_object("start")
self.progressbar = self.builder.get_object("progressbar")
self.image1=self.builder.get_object("image1")
self.image2=self.builder.get_object("image2")
self.malaria.set_sensitive(True)
self.dengue.set_sensitive(True)
self.tuberculosis.set_sensitive(True)
self.spherocytosis.set_sensitive(False)
self.sicklecellanemia.set_sensitive(False)
self.hereditaryelliptocytosis.set_sensitive(False)
def on_infectiousdisease_toggled(self, button):
if button.get_active():
print "infectious"
self.malaria.set_sensitive(True)
self.dengue.set_sensitive(True)
self.tuberculosis.set_sensitive(True)
self.spherocytosis.set_sensitive(False)
self.sicklecellanemia.set_sensitive(False)
self.hereditaryelliptocytosis.set_sensitive(False)
#print "infectious"
def on_hematological_toggled(self, button):
if button.get_active():
print "hematology"
self.spherocytosis.set_sensitive(True)
self.sicklecellanemia.set_sensitive(True)
self.hereditaryelliptocytosis.set_sensitive(True)
self.malaria.set_sensitive(False)
self.dengue.set_sensitive(False)
self.tuberculosis.set_sensitive(False)
def on_completebloodcount_toggled(self, button):
global test
test="Complete Blood Count"
print "blood count"
self.spherocytosis.set_sensitive(False)
self.sicklecellanemia.set_sensitive(False)
self.hereditaryelliptocytosis.set_sensitive(False)
self.malaria.set_sensitive(False)
self.dengue.set_sensitive(False)
self.tuberculosis.set_sensitive(False)
self.hereditaryelliptocytosis.set_sensitive(False)
def on_malaria_toggled(self, widget):
if malaria.get_active():
global test
test="Malaria"
print "on"
#else:
# print "off"
def on_hereditaryelliptocytosis_toggled(self, widget):
if hereditaryelliptocytosis.get_active():
print "hereditaryelliptocytosis"
global test
test="hereditaryelliptocytosis"
def on_timeout_thread_end(self, user_data):
global error1
global error2
global error3
global filename
# Error handling if the Motor pulse giving Arduino board is missing
if error1==1:
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, "Error!")
dialog.format_secondary_text("Required hardware missing!.. Cannot run application")
response = dialog.run()
self.progressbar.set_fraction(0.0)
self.timeout_id = GObject.timeout_add(False, self.on_timeout,None)
if response == Gtk.ResponseType.OK:
self.window.close()
dialog.destroy()
self.window.hide()
Gtk.main_quit()
# Error handling if the camera is not operating properly
elif error2==1:
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, "Error!")
dialog.format_secondary_text("Camera interface not found!.. Cannot run application")
response = dialog.run()
self.progressbar.set_fraction(0.0)
self.timeout_id = GObject.timeout_add(False, self.on_timeout,None)
if response == Gtk.ResponseType.OK:
self.window.close()
dialog.destroy()
self.window.hide()
Gtk.main_quit()
elif error3==1:
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, "Sending Data Error!")
dialog.format_secondary_text("Cannot send data.")
response = dialog.run()
self.progressbar.set_fraction(0.0)
self.timeout_id = GObject.timeout_add(False, self.on_timeout,None)
if response == Gtk.ResponseType.OK:
self.window.close()
dialog.destroy()
self.window.hide()
Gtk.main_quit()
sys.exit()
else:
if self.Thread1.is_alive():
test_ended = False
else:
test_ended = True
text="Finished Sending Data !"
# text="Data Sent for Analysis"
self.progressbar.set_text(text)
self.activity=False
#print("send_data status=%s",SendCellDataThread)
self.progressbar.set_fraction(0.0)
self.timeout_id = GObject.timeout_add(1, self.on_timeout,None)
#self.progressbar.set_fraction(0.0)
GObject.source_remove(self.timeout_id)
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.YES_NO, "Test Complete !")
dialog.format_secondary_text("Do you want to run another test?")
response = dialog.run()
if response == Gtk.ResponseType.YES:
dialog.destroy()
self.window.hide()
Gtk.main_quit()
dialog.destroy()
if response == Gtk.ResponseType.NO:
dialog.destroy()
#os.system('rm ./celldata.zip')
dialog.destroy()
self.window.hide()
Gtk.main_quit()
sys.exit()
return False
return True
#print("Button", "was turned", state)
def on_start_clicked(self, widget):
global count
global ExitVLCThread
global Acquire
global Kill
global SendCellDataThread
global test
global st
global name
global age
global patientID
global filename
folder=("/home/odroid/BloodAnalyser/AcquiredData/")
#filename=folder.append(st)
#filename=filename.append(".txt")
filename=folder+'PatientInformation'+".txt"
f = open(filename,"w") #opens file with name of "test.txt"
#f.write("Name:\t")
f.write(name)
f.write("\n")
print(f)
#f.write("Age:\t")
f.write(age)
f.write("\n")
#f.write("PatientID:\t")
f.write(patientID)
f.write("\n")
#f.write("Test Selected:\t")
f.write(test)
f.write("\n")
f.close()
#os.system('7z a /home/odroid/BloodAnalyser/AcquiredData/celldata.7z /home/odroid/BloodAnalyser/AcquiredData/PatientInformation')
#self.activity= False
#self.ftp_invoke()
count=count+1
print(count)
if (count ==1):
print("Hello World!")
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.YES_NO, "Reminder! Suitable Cartridge had to be loaded before starting the test.")
dialog.format_secondary_text("Do you want to continue?")
response = dialog.run()
if response == Gtk.ResponseType.YES:
dialog.destroy()
self.start.set_label("ABORT TEST")
print("WARN dialog closed by clicking OK button")
Acquire = True
print (Acquire)
#Kill = True
#print(Kill)
#global Thread1
#global Thread2
auto_focus=AutoFocus()
#auto_focus.window.show()
#blood_analyser = BloodAnalyser()
self.timeout_id_thread_end = GObject.timeout_add(500, self.on_timeout_thread_end, None)
self.Thread1=threading.Thread(target=auto_focus.pulse_invoke)
#self.Thread1.start()
#self.Thread1=threading.Thread(target=self.vlc_invoke)
self.Thread1.daemon=True
self.Thread1.start()
elif response == Gtk.ResponseType.NO:
dialog.destroy()
print("WARN dialog closed by clicking CANCEL button")
count=0
else:
print(count)
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING,Gtk.ButtonsType.YES_NO, "Test in progress!.. Do you still want to abort test?")
dialog.format_secondary_text("Click Yes to continue")
response = dialog.run()
if response == Gtk.ResponseType.YES:
dialog.destroy()
self.window.hide()
Gtk.main_quit()
os.system('exit()')
print("Thread2=")
print(SendCellDataThread)
os.system("killall vlc")
self.start.set_label("START TEST")
text2 = " "
count = 0
self.progressbar.set_text(text2)
self.progressbar.set_show_text(text2)
self.progressbar.set_fraction(0.0)
self.activity= False
# self.timeout_id = GObject.timeout_add(0, self.on_timeout,None)
self.start.set_label("START TEST")
#os.system('rm ./celldata.zip')
os.system('rm -r ./AcquiredData')
os.system('mkdir ./AcquiredData')
print("WARN dialog closed by clicking OK button")
elif response == Gtk.ResponseType.NO:
count = 0
dialog.destroy()
def on_timeout(self, user_data):
if self.activity:
new_value = self.progressbar.get_fraction() + 0.01
if new_value > 1:
new_value = 0
self.progressbar.set_fraction(new_value)
return True
def vlc_invoke(self):
#gobject.threads_init()
#os.system("v4l2-ctl -c exposure_absolute=1")
print ("Vlc invoked")
#similar to time.sleep()
#sleep(10)
n = 0
global error2
start_time=time.time()
while (True):
sleep(0.5)
print Acquire
if Acquire:
#print ('while acquire')
self.activity= 1
self.timeout_id = GObject.timeout_add(400, self.on_timeout,None)
os.chdir('/home/odroid/BloodAnalyser/AcquiredData')
itime=time.time()
i=1
print("Time taken to capture =")
print(time.time()-itime)
os.chdir('/home/odroid/BloodAnalyser/AcquiredData')
while(i<batches+1):
text2 = "Acquiring Dataset %d"%i
self.progressbar.set_text(text2)
self.progressbar.set_show_text(text2)
os.mkdir('/home/odroid/BloodAnalyser/AcquiredData/%d'%i)
os.chdir('/home/odroid/BloodAnalyser/AcquiredData/%d'%i)
os.system("mplayer tv:// -tv driver=v4l2:device=/dev/video0:fps=60 --frames=%d -vo jpeg"%numframes)
if i==1:
ip=ip1
elif i==batches:
ip=ip2
os.system('7z a /home/odroid/BloodAnalyser/AcquiredData/celldata%d.7z /home/odroid/BloodAnalyser/AcquiredData/%d'%(i,i))
self.sizewrite(i,ip)
os.system("echo odroid | sudo -S scp -i /home/odroid/jayesh1.pem /home/odroid/BloodAnalyser/AcquiredData/celldata%d.7z ubuntu@%s:"%(i,ip2))
print('File Uploaded to %s'%ip)
return
a=thread.start_new_thread(self.compress,(i,ip))
i=i+1
print 'Updating queue'
self.start.set_sensitive(False)
def compress(self,i,ip):
text='Compessing and Sending Dataset %d'%i
self.progressbar.set_text(text)
print ('Entered Compression=%d'%i)
self.progressbar.set_show_text(text)
os.chdir('/home/odroid/BloodAnalyser/AcquiredData/')
print(name)
start_time=time.time()
#if i==1:
os.system('7z a /home/odroid/BloodAnalyser/AcquiredData/celldata%d.7z /home/odroid/BloodAnalyser/AcquiredData/%d'%(i,i))
self.sizewrite(i,ip)
os.system("echo odroid | sudo -S scp -i /home/odroid/jayesh1.pem /home/odroid/BloodAnalyser/AcquiredData/PatientInformation.txt /home/odroid/BloodAnalyser/AcquiredData/celldata%d.7z ubuntu@%s:"%(i,ip))
print('File Uploaded to %s'%ip)
print("--- %s seconds ---" % (time.time() - start_time))
def sizewrite(self,i,ip):
print "entered write size"
size=str(os.path.getsize('/home/odroid/BloodAnalyser/AcquiredData/celldata%d.7z'%i))
print ("size of %d file is:%s"%(i,size))
f=open('/home/odroid/BloodAnalyser/AcquiredData/sizefile.txt','w')
f.write(size)
f.close()
os.system("echo odroid | sudo -S scp -i /home/odroid/jayesh1.pem /home/odroid/BloodAnalyser/AcquiredData/sizefile.txt ubuntu@%s:"%ip)
return
if __name__ == "__main__":
#patient_ID=patientID()
blood_analyser = BloodAnalyser()
splScr = splashScreen()
patient_ID=patientID()
#quitwindow=quit_window()
#If you don't do this, the splash screen will show, but wont render it's contents
while Gtk.events_pending():
Gtk.main_iteration()
GObject.timeout_add(5000, splScr.window.hide)
Gtk.main()