Ejemplo n.º 1
0
	def __init__(self,record):
		# quiz variables:
		#	playback is valable for non-standalone marked quiz
		# 	assume standalone is false
		self.practice_mode = False
		self.standalone = False
		self.logged = True
		self.log_dir = ''
		self.question_list = []
		self.answer_list = []
		self.message_list = []
		self.mark_list = []
		
		L = record.keys()
		L.sort()
		for k in L:
			q = record[k]
			path = q[0]
			answer = q[1]
			result = q[2]
			message = 'Correct'
			if result == 0:
				message = 'Incorrect'
			types = os.path.join(path,'types.py')
			try:
				exec(open(types,'r').read())
				# construct question object
				exec('import question.'+product_family)
				exec('question_obj = question.'+product_family+'.'+question_type+'(path)')
			except:
				errorlog.write("fatal: quiz spec OK, but question "+str(q)+" is problematic")
			self.question_list.append(question_obj)
			self.answer_list.append(answer)
			self.message_list.append(message)
			self.mark_list.append(result)
Ejemplo n.º 2
0
def checkCameras():
  oddFound = False
  evenFound = False
  tooManyCameras = False
  cameraList = camera.search()
  #cameraList = [0,0]
  try:
    if len(cameraList) > 2:
      tooManyCameras = True
    else:
      for item in cameraList:
        if item.serial_num == odd.serial:
          if not odd.camera.is_connected():
            odd.reset(item)
        elif item.serial_num == even.serial:
          if not even.camera.is_connected():
            even.reset(item)
        elif odd.camera is None or not odd.camera.is_connected():
          odd.reset(item)
        elif even.camera is None or not even.camera.is_connected():
          even.reset(item)
      oddFound = odd.camera is not None and odd.camera.is_connected()
      evenFound = even.camera is not None and even.camera.is_connected()
  except Exception as e:
    errorlog.write('Failed to reset cameras: ' + str(e.args) + '\n' + traceback.format_exc())
  return (oddFound, evenFound, tooManyCameras)
Ejemplo n.º 3
0
def saveConfig(mountPoint):
    filename = mountPoint + "/pi-scan.conf"
    jsonText = json.dumps(config, sort_keys=True, indent=2, separators=(",", ": "))
    try:
        fp = open(filename, "w")
        fp.write(jsonText)
        fp.close()
    except Exception as e:
        errorlog.write("Failed to write config file: " + str(e) + ": " + str(e.args))
Ejemplo n.º 4
0
def saveConfig(mountPoint):
  filename = mountPoint + '/pi-scan.conf'
  jsonText = json.dumps(config, sort_keys=True, indent=2, separators=(',', ': '))
  try:
    fp = open(filename, 'w')
    fp.write(jsonText)
    fp.close()
  except Exception as e:
    errorlog.write('Failed to write config file: ' + str(e) + ': ' + str(e.args))
Ejemplo n.º 5
0
def search():
  result = []
  try:
    devices = chdkptp.list_devices()
    if devices is not None:
      for info in chdkptp.list_devices():
        result.append(info)
  except LuaError as e:
    errorlog.write('Failed to search: LuaError: ' + str(e.args) + '\nTraceback: ' + traceback.format_exc())
  except Exception as e:
    errorlog.write('Failed to search: ' + str(e.args) + '\n' + traceback.format_exc())
  return result
Ejemplo n.º 6
0
  def process(self, raw):
    result = PreviewResult()
    result.code = FAILED
    try:
      # Load full image from raw binary representation
      result.message = 'Failed to load image'
      stream = StringIO.StringIO(raw)
      full = PillowImage.open(stream)
      #full = JPEGImage(blob=raw)

      # Rotate the full image for preview
      if self.position == 'odd':
        full = full.transpose(PillowImage.ROTATE_270)
        #full = full.rotate(-90)
      elif self.position == 'even':
        full = full.transpose(PillowImage.ROTATE_90)
        #full = full.rotate(90)

      # Set size parameters based on the full image
      #result.message = 'Failed to calculate size parameters'
      result.width = full.size[0]
      #result.width = full.width
      result.height = full.size[1]
      #result.height = full.height
      result.columnCount = int(math.ceil(result.width / 2000.0))
      rowCount = int(math.ceil(result.height / 2000.0))

      # Populate the cropped core images for later preview
      result.data = []
      result.sizes = []
      for y in xrange(rowCount-1, -1, -1):
        for x in xrange(result.columnCount-1, -1, -1):
          result.message = 'Failed to crop base image'
          #width = min(result.width - x*2000, 2000)
          #height = min(result.height - y*2000, 2000)
          #croppedJpeg = full.crop(x*2000, y*2000, width, height)
          #stream = StringIO.StringIO(croppedJpeg.as_blob())
          #cropped = PillowImage.open(stream)
          right = min((x+1)*2000, result.width)
          lower = min((y+1)*2000, result.height)
          cropBox = (x*2000, y*2000, right, lower)
          cropped = full.crop(cropBox)
          result.message = 'Failed to turn cropped image into texture'
          data = CoreImageData(cropped.size[0], cropped.size[1],
                               cropped.mode.lower(), cropped.tobytes())
          result.data.append(data)
          result.sizes.append(cropped.size)
      result.code = COMPLETE
    except Exception as e:
      errorlog.write('Failed to process: ' + result.message + ': ' + str(e) + ': ' + str(e.args))
    return result
Ejemplo n.º 7
0
def parseCameras(text):
    result = []
    lines = text.split('\n')
    for line in lines[2:]:
        if line != '':
            test = re.compile('(usb:[0-9,]+)')
            match = test.search(line)
            if match is not None:
                usb_port = match.group(1)
                serial_num = getConfig(usb_port, '/main/status/serialnumber')
                result.append(GphotoInfo(usb_port, serial_num))
            else:
                errorlog.write('Failed to parse camera line: ' + line)
    return result
Ejemplo n.º 8
0
def checkForDisconnected(manager):
    # Proactively detect when cameras are disconnected or crash
    if odd.camera is None or not odd.camera.is_connected():
        odd.code = camera_thread.DISCONNECTED
        odd.message = 'Lost Connection to Camera'
        errorlog.write('odd camera: ' + odd.message)
    if even.camera is None or not even.camera.is_connected():
        even.code = camera_thread.DISCONNECTED
        even.message = 'Lost Connection to Camera'
        errorlog.write('even camera: ' + even.message)
    if odd.code == camera_thread.DISCONNECTED or even.code == camera_thread.DISCONNECTED:
        manager.capturePage = 'focus-camera'
        manager.transition.direction = 'left'
        manager.current = 'debug'
Ejemplo n.º 9
0
def loadConfig(mountPoint):
    global config
    config = {}
    filename = mountPoint + "/pi-scan.conf"
    jsonText = ""
    try:
        fp = open(filename, "r")
        jsonText = fp.read()
        fp.close()
        config = json.loads(jsonText)
        odd.loadConfig(config)
        even.loadConfig(config)
    except Exception as e:
        errorlog.write("Failed to read config file: " + str(e) + ": " + str(e.args) + "\n\n" + jsonText)
Ejemplo n.º 10
0
def loadConfig(mountPoint):
  global config
  config = {}
  filename = mountPoint + '/pi-scan.conf'
  jsonText = ''
  try:
    fp = open(filename, 'r')
    jsonText = fp.read()
    fp.close()
    config = json.loads(jsonText)
    odd.loadConfig(config)
    even.loadConfig(config)
  except Exception as e:
    errorlog.write('Failed to read config file: ' + str(e) + ': ' + str(e.args) + '\n\n' + jsonText)
Ejemplo n.º 11
0
def loadConfig(mountPoint):
  global config
  config = {}
  filename = mountPoint + '/pi-scan.conf'
  jsonText = ''
  try:
    fp = open(filename, 'r')
    jsonText = fp.read()
    fp.close()
    config = json.loads(jsonText)
    odd.loadConfig(config)
    even.loadConfig(config)
  except Exception as e:
    errorlog.write('Failed to read config file: ' + str(e) + ': ' + str(e.args) + '\n\n' + jsonText)
Ejemplo n.º 12
0
def search():
    result = []
    try:
        devices = chdkptp.list_devices()
        if devices is not None:
            for info in chdkptp.list_devices():
                result.append(info)
    except LuaError as e:
        errorlog.write('Failed to search: LuaError: ' + str(e.args) +
                       '\nTraceback: ' + traceback.format_exc())
    except Exception as e:
        errorlog.write('Failed to search: ' + str(e.args) + '\n' +
                       traceback.format_exc())
    return result
Ejemplo n.º 13
0
def checkForDisconnected(manager):
  # Proactively detect when cameras are disconnected or crash
  if odd.camera is None or not odd.camera.is_connected():
    odd.code = camera_thread.DISCONNECTED
    odd.message = 'Lost Connection to Camera'
    errorlog.write('odd camera: ' + odd.message)
  if even.camera is None or not even.camera.is_connected():
    even.code = camera_thread.DISCONNECTED
    even.message = 'Lost Connection to Camera'
    errorlog.write('even camera: ' + even.message)
  if odd.code == camera_thread.DISCONNECTED or even.code == camera_thread.DISCONNECTED:
    manager.capturePage = 'focus-camera'
    manager.transition.direction = 'left'
    manager.current = 'debug'
Ejemplo n.º 14
0
    def __init__(self, quiz_spec):
        # import quiz_spec_file
        if not re.match("^[a-zA-Z0-9_/]*$", quiz_spec):
            errorlog.write("bad quiz name passed in URL: " + quiz_spec)
            raise IOError
        quiz_dir, quiz_name = os.path.split(quiz_spec)
        sys.path.append(os.path.abspath(os.path.join("../quizzes", quiz_dir)))
        quiz_spec_file = __import__(quiz_name)

        for i in ['practice_mode', 'standalone', 'logged', 'log_dir']:
            setattr(self, i, getattr(quiz_spec_file, i))

        self.log_name = ''
        self.question_list = []
        self.answer_list = []
        self.message_list = []
        self.mark_list = []
        self.question_lib_path = "../question_library/"
        if 'question_library' in dir(quiz_spec_file):
            self.question_lib_path = quiz_spec_file.question_library

        for q in get_questions(quiz_spec_file.question_list,
                               self.question_lib_path):
            config_file = os.path.join(self.question_lib_path, q[1],
                                       'cqg_config.py')
            try:
                config = file_util.dynamic_import(config_file)
                # construct question object
                exec('import question.' + config.product_family)
                exec('question_obj = question.' + config.product_family + '.' +
                     config.question_type + '(self.question_lib_path,q[1])')
            except:
                trace = traceback.format_exc()
                errorlog.write("fatal: quiz spec OK, but question " + str(q) +
                               " is problematic; full trace:\n" + trace)
            self.question_list.append(question_obj)
            blank_answer = {}
            for k in question_obj.get_input_element_ids():
                blank_answer[k] = None
            self.answer_list.append(blank_answer)
            self.message_list.append('')
            self.mark_list.append(q[0])
Ejemplo n.º 15
0
	def __init__(self,quiz_spec):
		# import quiz_spec_file
		if not re.match("^[a-zA-Z0-9_/]*$",quiz_spec):
			errorlog.write("bad quiz name passed in URL: "+quiz_spec)
			raise IOError
		quiz_dir,quiz_name = os.path.split(quiz_spec)
		sys.path.append(os.path.abspath(os.path.join("../quizzes",
		 quiz_dir)))
		quiz_spec_file = __import__(quiz_name)

		for i in ['practice_mode','standalone','logged','log_dir']:
			setattr(self,i,getattr(quiz_spec_file,i))
		
		self.log_name = ''
		self.question_list = []
		self.answer_list = []
		self.message_list = []
		self.mark_list = []
		self.question_lib_path = "../question_library/"
		if 'question_library' in dir(quiz_spec_file):
			self.question_lib_path = quiz_spec_file.question_library

		for q in get_questions(quiz_spec_file.question_list,self.question_lib_path):
			config_file = os.path.join(self.question_lib_path,q[1],'cqg_config.py')
			try:
				config = file_util.dynamic_import(config_file)
				# construct question object
				exec('import question.'+config.product_family)
				exec('question_obj = question.'+config.product_family+'.'+config.question_type+'(self.question_lib_path,q[1])')
			except:
				trace = traceback.format_exc()
				errorlog.write("fatal: quiz spec OK, but question "+str(q)+" is problematic; full trace:\n"+trace)
			self.question_list.append(question_obj)
			blank_answer = {}
			for k in question_obj.get_input_element_ids():
				blank_answer[k] = None
			self.answer_list.append(blank_answer)
			self.message_list.append('')
			self.mark_list.append(q[0])
Ejemplo n.º 16
0
    def __init__(self, record):
        # quiz variables:
        #	playback is valable for non-standalone marked quiz
        # 	assume standalone is false
        self.practice_mode = False
        self.standalone = False
        self.logged = True
        self.log_dir = ''
        self.question_list = []
        self.answer_list = []
        self.message_list = []
        self.mark_list = []

        L = record.keys()
        L.sort()
        for k in L:
            q = record[k]
            path = q[0]
            answer = q[1]
            result = q[2]
            message = 'Correct'
            if result == 0:
                message = 'Incorrect'
            types = os.path.join(path, 'types.py')
            try:
                exec(open(types, 'r').read())
                # construct question object
                exec('import question.' + product_family)
                exec('question_obj = question.' + product_family + '.' +
                     question_type + '(path)')
            except:
                errorlog.write("fatal: quiz spec OK, but question " + str(q) +
                               " is problematic")
            self.question_list.append(question_obj)
            self.answer_list.append(answer)
            self.message_list.append(message)
            self.mark_list.append(result)
Ejemplo n.º 17
0
 def ok(self):
     try:
         #odd.code = camera_thread.COMPLETE
         #even.code = camera_thread.COMPLETE
         errorlog.write('FAIL: before ok')
         errorlog.write('FAIL: capturePage: ' + self.manager.capturePage)
         self.manager.transition.direction = 'left'
         self.manager.current = self.manager.capturePage
         errorlog.write('FAIL: after ok')
     except Exception as e:
         handleCrash(e)
Ejemplo n.º 18
0
 def ok(self):
   try:
     #odd.code = camera_thread.COMPLETE
     #even.code = camera_thread.COMPLETE
     errorlog.write('FAIL: before ok')
     errorlog.write('FAIL: capturePage: ' + self.manager.capturePage)
     self.manager.transition.direction = 'left'
     self.manager.current = self.manager.capturePage
     errorlog.write('FAIL: after ok')
   except Exception as e:
     handleCrash(e)
Ejemplo n.º 19
0
 def on_pre_enter(self):
   try:
     if debug:
       errorlog.write('FAIL: Before labels')
     self.evenLabel.text = 'Even Camera: '
     self.oddLabel.text = 'Odd Camera: '
     self.updateLabel(self.evenLabel, even)
     self.updateLabel(self.oddLabel, odd)
     if debug:
       errorlog.write('FAIL: Before beeps')
     even.camera.beepFail()
     odd.camera.beepFail()
     errorlog.write('FAIL: After pre_enter')
   except Exception as e:
     handleCrash(e)
Ejemplo n.º 20
0
 def on_pre_enter(self):
     try:
         if debug:
             errorlog.write('FAIL: Before labels')
         self.evenLabel.text = 'Even Camera: '
         self.oddLabel.text = 'Odd Camera: '
         self.updateLabel(self.evenLabel, even)
         self.updateLabel(self.oddLabel, odd)
         if debug:
             errorlog.write('FAIL: Before beeps')
         even.camera.beepFail()
         odd.camera.beepFail()
         errorlog.write('FAIL: After pre_enter')
     except Exception as e:
         handleCrash(e)
Ejemplo n.º 21
0
 def update(self, dt):
   if debug:
     errorlog.write('FAIL: Update')
Ejemplo n.º 22
0
 def log(self, message):
   errorlog.write(self.position + ' camera: ' + message + ' -- self.message: ' + self.message)
Ejemplo n.º 23
0
 def log(self, message):
     errorlog.write(self.position + ' camera: ' + message +
                    ' -- self.message: ' + self.message)
Ejemplo n.º 24
0
 def update(self, dt):
     if debug:
         errorlog.write('FAIL: Update')
Ejemplo n.º 25
0
    def on_pre_enter(self):
        try:
            errorlog.write('CAPTURE: on_pre_enter')
            self.isCapturing = False
            if self.manager.newCapture:
                errorlog.write('CAPTURE: newCapture is true')
                self.manager.newCapture = False
                if (odd.code == camera_thread.COMPLETE
                        and even.code == camera_thread.COMPLETE):
                    errorlog.write('CAPTURE: both are COMPLETE')
                    self.lastEvenPage = self.nextEvenPage
                    self.nextEvenPage += 2
                    self.captureLabel.text = 'Captured Pages ' + str(
                        self.lastEvenPage) + ', ' + str(self.lastEvenPage + 1)
                    self.rescanButton.disabled = False
                else:
                    errorlog.write('CAPTURE: one or both are failure')
                    self.captureLabel.text = 'Ready For Capture'
                    self.rescanButton.disabled = True
                odd.code = camera_thread.COMPLETE
                even.code = camera_thread.COMPLETE

            if self.manager.newPreview:
                errorlog.write('CAPTURE: newPreview is true')
                self.manager.newPreview = False
                self.preview.opacity = 1.0
                self.previewButton.opacity = 0.0
                self.previewButton.disabled = True
            else:
                errorlog.write('CAPTURE: newPreview is false')
                self.preview.opacity = 0.0
                if self.lastEvenPage is not None:
                    self.previewButton.opacity = 1.0
                    self.previewButton.disabled = False
                else:
                    self.previewButton.opacity = 0.0
                    self.previewButton.disabled = True

            errorlog.write('CAPTURE: before resetPages()')
            if self.nextEvenPage is None:
                self.resetPages()
            errorlog.write('CAPTURE: on_pre_enter complete')

        except Exception as e:
            handleCrash(e)
Ejemplo n.º 26
0
  def on_pre_enter(self):
    try:
      errorlog.write('CAPTURE: on_pre_enter')
      self.isCapturing = False
      if self.manager.newCapture:
        errorlog.write('CAPTURE: newCapture is true')
        self.manager.newCapture = False
        if (odd.code == camera_thread.COMPLETE and
            even.code == camera_thread.COMPLETE):
          errorlog.write('CAPTURE: both are COMPLETE')
          self.lastEvenPage = self.nextEvenPage
          self.nextEvenPage += 2
          self.captureLabel.text = 'Captured Pages ' + str(self.lastEvenPage) + ', ' + str(self.lastEvenPage + 1)
          self.rescanButton.disabled = False
        else:
          errorlog.write('CAPTURE: one or both are failure')
          self.captureLabel.text = 'Ready For Capture'
          self.rescanButton.disabled = True
        odd.code = camera_thread.COMPLETE
        even.code = camera_thread.COMPLETE

      if self.manager.newPreview:
        errorlog.write('CAPTURE: newPreview is true')
        self.manager.newPreview = False
        self.preview.opacity = 1.0
        self.previewButton.opacity = 0.0
        self.previewButton.disabled = True
      else:
        errorlog.write('CAPTURE: newPreview is false')
        self.preview.opacity = 0.0
        if self.lastEvenPage is not None:
          self.previewButton.opacity = 1.0
          self.previewButton.disabled = False
        else:
          self.previewButton.opacity = 0.0
          self.previewButton.disabled = True

      errorlog.write('CAPTURE: before resetPages()')
      if self.nextEvenPage is None:
        self.resetPages()
      errorlog.write('CAPTURE: on_pre_enter complete')

    except Exception as e:
      handleCrash(e)