Esempio n. 1
0
    def onAddNewUserButtonPressed(self, button):
        
        db = sqlite3.connect('SaedRobot.db')
        
        c = db.cursor()
        c1 = db.cursor()
        
        c.execute('SELECT * from users WHERE username= ? ' , (str(self.username.get_text()),))
        data=c.fetchall()
        
        c1.execute('SELECT * from users WHERE email= ? ' , (str(self.email.get_text()),))
        data1=c1.fetchall()
        
        if len(str(self.username.get_text())) == 0:
           dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK, "No username entered, please enter a username")
           dialog.set_title("Error message")
           dialog.run()
           dialog.close()
           
        elif len(str(self.email.get_text())) == 0:
           dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK, "No email entered, please enter an email")
           dialog.set_title("Error message")
           dialog.run()
           dialog.close()
           
        elif len(data)>0:
           dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK, "This username is already exist!")
           dialog.set_title("Error message")
           dialog.run()
           dialog.close()
             
        elif len(data1)>0:
           dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK, "This email is already exist!")
           dialog.set_title("Error message")
           dialog.run()
           dialog.close()
           
        elif not re.match("^[a-zA-Z0-9_]+$", str(self.username.get_text())):
           dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK, "Invalid username address, please enter a valid username.")
           dialog.set_title("Error message")
           dialog.run()
           dialog.close()      
                          
        elif not validate_email(str(self.email.get_text())):
           dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK, "Invalid email address, please enter a valid address.")
           dialog.set_title("Error message")
           dialog.run()
           dialog.close()
           
        else:
			 password = id_generator()
			 c.execute('INSERT INTO users(USERNAME,PASSWORD,EMAIL,ADMIN) VALUES (?,?,?,0)', (str(self.username.get_text()),str(password),str(self.email.get_text())))
			 db.commit()
			 send_email(password,self.username.get_text(),"Saed Robot - Registration Confirmation",str(self.email.get_text()) )
			 dialog = Gtk.MessageDialog(None,0,Gtk.MessageType.INFO,Gtk.ButtonsType.OK, "The user has been added")
			 dialog.set_title("Confirmation message")
			 dialog.run()
			 dialog.close()
			 self.window.destroy()
			 self.window=ManageUsersAccounts.ManageUsersAccounts(self.MyUsername, self.userType)
Esempio n. 2
0
	def reset(self,button):
		email = self.builder.get_object("email") # get the value from the field
		db = sqlite3.connect('SaedRobot.db')
		
		c = db.cursor()
		# query the DB if such an email exist
		c.execute('SELECT * from users WHERE email=?' , (email.get_text(),))
		row=c.fetchone()
		
		# check+send the new password
		if row != None and len(row)>0:
			username = row[0]
			randPassword= id_generator()
			c = db.cursor()
			c.execute("update users set password=? where username=?" , (randPassword,username,))
			db.commit()
			send_email(randPassword,username,"Saed Robot - Reset your password",email.get_text() )
			dialog=Gtk.MessageDialog(None,0,Gtk.MessageType.INFO,Gtk.ButtonsType.OK,"Your new password has been sent to your email")
			dialog.set_title("Confirmation message")
			dialog.run()
			dialog.close()
			self.window.destroy()
			self.window=login.loginClass()

		# show error message if no such email exists
		else:
			dialog=Gtk.MessageDialog(None,0,Gtk.MessageType.ERROR,Gtk.ButtonsType.OK,"Invalid entry, please try again")
			dialog.set_title("Error message")
			dialog.run()
			dialog.close()
Esempio n. 3
0
def parse_annon_filename(filepath):
    """Annotation file names are semantically named such that it empowers for different
  types of annotations in computer vision tasks to be carried out without duplicating
  the images on the filesystem. And, different annotators can annotate same image for
  different type of annotation tasks like for detection, classification, scene type, keypoint annoations etc.
  This also empower for generating different statistics for tracking and management.

  Semantics of annotation file name is illustrated below:
  # --------------------------------------------------------

  * example: Annotation file is saved with the name: `images-p1-230119_AT1_via205_010219.json`
  
  Level-1: After removing the file extension, split with '_' (underscore)
    * returns 4 groups (or Level 2) indexed
    * ex: [0,1,2,3] => ['images-p1-230119', 'AT1', 'via205', '010219'], where:
          'images-p1-230119' => Reference to `image folder` used for the annotations present in this file
          'AT1' => Annotator ID
          'via205' => Annotation tool with version; here VIA annotation tool and version 2.05
          '010219' => Release date on which the annotation file was provided by the annotator
    * additionally, joining [0,1] back with '_' (underscore) provides the reference for directory under which images are present
          ex: [0,1] => ['images-p1-230119', 'AT1'] joining it back with '_' (underscore) gives: 'images-p1-230119_AT1'
  
  Level-2: For each Level 1 items can be split with '-' (minus) wherever possible (absence of this will not result in error during split)
    * ex: 'images-p1-230119' => ['images','p1','230191'], where:
      'images' => directory name under which images would be allocated.
      'p1' => part ID of the images
      '230191' => date on which the images cut was taken and assigned to the annotators
  """

    name = os.path.basename(filepath)
    try:
        ref = os.path.splitext(name)[0].split('_')
        ref_img = ref[0].split('-')
        name_ids = {
            "image_rel_date": str(ref_img[2]),
            "image_part": "-".join(ref_img[:2]),
            "annotator_id": ref[1],
            "annotation_rel_date": str(ref[3]),
            "annotation_tool": ref[2],
            "image_dir": '_'.join(ref[:2]),
            "rel_filename": name
        }
    except Exception as e:
        log.info(
            "Unable to parse annontation filename, hence falling back to defaults",
            exc_info=True)
        name_ids = {
            "image_rel_date": common.modified_on(filepath, True),
            "image_part": None,
            "annotator_id": common.id_generator(5),
            "annotation_rel_date": common.timestamp(),
            "annotation_tool": None,
            "image_dir": os.path.dirname(filepath),
            "rel_filename": name
        }

    log.info("name_ids: {}".format(name_ids))

    return name_ids
Esempio n. 4
0
def asking_question():
    if request.method == 'GET':
        return render_template('ask_a_question_form.html')
    elif request.method == 'POST':
        lines = data_manager.read_file('question.csv')
        data_dict = request.form.to_dict()
        data_list = [
            common.id_generator('question.csv'), data_dict['question_title'],
            data_dict['question_detail'], data_dict['category'],
            time.asctime(time.localtime(time.time()))
        ]

        lines.append(data_list)

        data_manager.write_in_file('question.csv', lines)
        return redirect('/')
Esempio n. 5
0
def AddToDownloadsList(title, year, url, durl, purl, summary, thumb, quality, source, type, resumable, source_meta, file_meta, sub_url=None, fsBytes=None, fs=None, file_ext=None, vidtype=None, section_path=None, section_title=None, section_key=None, session=None, admin=False, update=False, user=None, params=None, riptype=None, **kwargs):

	admin = True if str(admin) == 'True' else False
	update = True if str(update) == 'True' else False
	resumable = True if str(resumable) == 'True' else False
	
	#Log(common.DOWNLOAD_OPTIONS_SECTION_TEMP)
	tuec = E(title+year+quality+source+url)
	
	if resumable != None and str(resumable).lower() == 'true':
		resumable = True
	else:
		resumable = False
	
	if section_path == None:
	
		time.sleep(2)
		
		DOWNLOAD_OPTIONS_SECTION_TEMP = Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec]
		
		if type not in DOWNLOAD_OPTIONS_SECTION_TEMP.keys() or len(DOWNLOAD_OPTIONS_SECTION_TEMP[type]) == 0:
			if 'Done' in DOWNLOAD_OPTIONS_SECTION_TEMP.keys():
				del Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec]
				Dict.Save()
				return MC.message_container('Download Sources', 'Item in Downloads Queue... Please return to previous screen.')
			if 'Error' in DOWNLOAD_OPTIONS_SECTION_TEMP.keys():
				del Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec]
				Dict.Save()
				return MC.message_container('Error', 'Error... Please return to previous screen.')
			return MC.message_container('Download Sources', 'No Download Locations set under Download Options')	
		elif 'Done' in DOWNLOAD_OPTIONS_SECTION_TEMP.keys():
			Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec] = {}
			Dict.Save()
			return MC.message_container('Download Sources', 'Item in Downloads Queue... Please return to previous screen.')
		elif 'Error' in DOWNLOAD_OPTIONS_SECTION_TEMP.keys():
			Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec] = {}
			Dict.Save()
			return MC.message_container('Download Sources', 'Error... Please return to previous screen.')
		elif type in DOWNLOAD_OPTIONS_SECTION_TEMP and len(DOWNLOAD_OPTIONS_SECTION_TEMP[type]) > 0:
			LOCS = []
			for item in DOWNLOAD_OPTIONS_SECTION_TEMP[type]:
				if item['enabled']:
					LOCS.append(item)
			if len(LOCS) == 1:
				item = LOCS[0]
				return AddToDownloadsList(title=title, year=year, url=url, durl=durl, purl=purl, summary=summary, thumb=thumb, fs=fs, fsBytes=fsBytes, file_ext=file_ext, quality=quality, source=source, source_meta=source_meta, file_meta=file_meta, type=type, vidtype=vidtype, resumable=resumable, sub_url=sub_url, section_path=item['path'], section_title=item['title'], section_key=item['key'], session=session, admin=admin, update=update, user=user, params=params, riptype=riptype)
			else:
				oc = ObjectContainer(title1='Select Location', no_cache=common.isForceNoCache())
				for item in DOWNLOAD_OPTIONS_SECTION_TEMP[type]:
					if item['enabled']:
						oc.add(DirectoryObject(
							key = Callback(AddToDownloadsList, title=title, year=year, url=url, durl=durl, purl=purl, summary=summary, thumb=thumb, fs=fs, fsBytes=fsBytes, file_ext=file_ext, quality=quality, source=source, source_meta=source_meta, file_meta=file_meta, type=type, vidtype=vidtype, resumable=resumable, sub_url=sub_url, section_path=item['path'], section_title=item['title'], section_key=item['key'], session=session, admin=admin, update=update, user=user, params=params, riptype=riptype),
							title = '%s | %s' % (item['title'], item['path'])
							)
						)
				if len(oc) == 0:
					return MC.message_container('Download Sources', 'No Download Location set under Download Options')
				return oc
	else:
		isPairDone = True
		pair_required = True
		try:
			if fs == None:
				if 'openload' in source:
					isPairDone = common.host_openload.isPairingDone()
					if isPairDone == False:
						pair_required, u1 = common.host_openload.isPairingRequired(url=url, session=session)
						if pair_required == False:
							fs_i, err = common.client.getFileSize(u1, retError=True, retry429=True, cl=2)
					online, r1, err, fs_i, r2, r3 =  common.host_openload.check(url, usePairing = False, embedpage=True)
				else:
					fs_i, err = common.client.getFileSize(url, retError=True, retry429=True, cl=2)

				if err != '':
					raise Exception(e)
					
				try:
					fsBytes = int(fs_i)
					fs = '%s GB' % str(round(float(fs_i)/common.TO_GB, 3))
				except:
					fsBytes = 0
					fs = '? GB'
					
			if int(fsBytes) < 100 * 1024:
				Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec] = {}
				Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec]['Error'] = 'Error'
				Dict.Save()
				return MC.message_container('FileSize Error', 'File reporting %s bytes cannot be downloaded. Please try again later when it becomes available.' % fsBytes)
				
			uid = 'Down5Split'+E(title+year+fs+quality+source)
			if Dict[uid] != None:
				if admin == True and update == True:
					pass
				else:
					Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec] = {}
					Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec]['Done'] = 'Done'
					Dict.Save()
					return MC.message_container('Download Sources', 'Item already in Downloads List')
					
			if file_ext == None:
				file_ext = '.mp4'

			chunk_size = int(1024.0 * 1024.0 * float(common.DOWNLOAD_CHUNK_SIZE)) # in bytes
			fid = '.'+common.id_generator()
			
			EncTxt = E(JSON.StringFromObject({'title':title, 'year':year, 'url':url, 'durl':durl, 'purl':purl, 'sub_url':sub_url, 'summary':summary, 'thumb':thumb, 'fsBytes':int(fsBytes), 'fs':fs, 'chunk_size':chunk_size, 'file_ext':file_ext, 'quality':quality, 'source':source, 'source_meta':source_meta, 'file_meta':file_meta, 'uid':uid, 'fid':fid, 'type':type, 'vidtype':vidtype, 'resumable':resumable, 'status':common.DOWNLOAD_STATUS[0], 'startPos':0, 'timeAdded':time.time(), 'first_time':time.time(), 'progress':0, 'chunk_speed':0,'avg_speed':0,'avg_speed_curr':0, 'eta':0, 'error':'', 'last_error':'Unknown Error', 'action':common.DOWNLOAD_ACTIONS[4],'section_path':section_path, 'section_title':section_title, 'section_key':section_key, 'user':user, 'params':params, 'riptype':riptype})) 
			Dict[uid] = EncTxt
			Dict.Save()
			Thread.Create(download.trigger_que_run)
		except Exception as e:
			err = '{}'.format(e)
			Log(err)
			return MC.message_container('Download Sources', 'Error %s when adding for Downloading ! Please try again later.' % err)
			
		Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec] = {}
		Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec]['Done'] = 'Done'
		Dict.Save()

		time.sleep(2)
		
		if 'openload' in source.lower() and isPairDone == False and pair_required == True:
			return MC.message_container('Download Sources', 'Successfully added but requires *Pairing* to Download')
		else:
			return MC.message_container('Download Sources', 'Successfully added to Download List')
Esempio n. 6
0
def AddToDownloadsListPre(title, year, url, durl, purl, summary, thumb, quality, source, type, resumable, source_meta, file_meta, mode, sub_url=None, fsBytes=None, fs=None, file_ext=None, vidtype=None, section_path=None, section_title=None, section_key=None, session=None, admin=False, update=False, params=None, riptype=None, **kwargs):
	
	admin = True if str(admin) == 'True' else False
	update = True if str(update) == 'True' else False
	resumable = True if str(resumable) == 'True' else False
	user = common.control.setting('%s-%s' % (session,'user'))
		
	bool = False
	for i_source in common.interface.getHosts(encode=False):
		if i_source['name'].lower() in source.lower() and i_source['downloading']:
			bool = True
			break

	if bool == False:
		return MC.message_container('Download Sources', 'No compatible Download service found for this URL !')
		
	title = common.cleantitle.windows_filename(title)
	tuec = E(title+year+quality+source+url)
		
	#if mode == common.DOWNLOAD_MODE[1]:
	if fs == None or fsBytes == None or int(fsBytes) == 0:
		err = ''
		try:
			if 'openload' in source:
				isPairDone = common.host_openload.isPairingDone()
				openload_vars =  common.host_openload.check(url, usePairing=False, embedpage=True)
				online, r1, err, fs_i, furl2, sub_url_t = openload_vars
				if sub_url == None:
					sub_url = sub_url_t
			elif 'rapidvideo' in source:
				vurl, r1, sub_url_t = common.host_rapidvideo.resolve(url, True)
				if sub_url == None:
					sub_url = sub_url_t
				fs_i, err = common.client.getFileSize(vurl, retError=True, retry429=True, cl=2)
			elif 'streamango' in source:
				vurl, r1, sub_url_t = common.host_streamango.resolve(url, True)
				if sub_url == None:
					sub_url = sub_url_t
				fs_i, err = common.client.getFileSize(vurl, retError=True, retry429=True, cl=2)
			else:
				fs_i, err = common.client.getFileSize(url, retError=True, retry429=True, cl=2)

			if err != '':
				return MC.message_container('Error', 'Error: %s. Please try again later when it becomes available.' % err)
				
			try:
				fsBytes = int(fs_i)
				fs = '%s GB' % str(round(float(fs_i)/common.TO_GB, 3))
			except:
				fsBytes = 0
				fs = '? GB'
				
			if int(fsBytes) < 100 * 1024:
				return MC.message_container('FileSize Error', 'File reporting %s bytes cannot be downloaded. Please try again later when it becomes available.' % fsBytes)

		except Exception as e:
			Log.Error('init.py > AddToDownloadsListPre : %s - %s' % (e,err))
			return MC.message_container('Error', '%s. Sorry but file could not be added.' % e)

	uid = 'Down5Split'+E(title+year+fs+quality+source)
	if Dict[uid] != None:
		EncTxt = Dict[uid]
		EncTxt = JSON.ObjectFromString(D(EncTxt))
		if admin == False and update == False:
			return MC.message_container('Download Sources', 'Item exists in Downloads List')
		elif admin == True and update == True and EncTxt['url'] != url:
			if uid in common.DOWNLOAD_STATS:
				return MC.message_container('Item Update', 'Cannot update a Downloading item.')
			
			EncTxt['url'] = url
			Dict[uid] = E(JSON.StringFromObject(EncTxt))
			Dict.Save()
			return MC.message_container('Item Update', 'Item has been updated with new download url')
		elif admin == True and update == False and EncTxt['url'] != url:
			oc = ObjectContainer(title1='Item exists in Downloads List', no_cache=common.isForceNoCache())
			oc.add(DirectoryObject(key = Callback(AddToDownloadsListPre, title=title, purl=purl, url=url, durl=durl, summary=summary, thumb=thumb, year=year, quality=quality, source=source, source_meta=source_meta, file_meta=file_meta, type=type, resumable=resumable, sub_url=sub_url, fsBytes=fsBytes, fs=fs, file_ext=file_ext, mode=mode, vidtype=vidtype, section_path=section_path, section_title=section_title, section_key=section_key, session=session, admin=admin, update=True, params=params, riptype=riptype), title = 'Update this item'))
			oc.add(DirectoryObject(key = Callback(MyMessage, title='Return', msg='Use back to Return to previous screen'), title = 'Return'))
			return oc
		elif admin == True and update == True and EncTxt['url'] == url:
			return MC.message_container('Item Updated', 'Item url updated.')
		elif admin == True and update == False and EncTxt['url'] == url:
			#return MC.message_container('Item Updated', 'Item url is up to date.')
			pass
		else:
			return MC.message_container('Item Updated', 'Please return to previous screen.')

		#uid = 'Request5Split'+E(title+year+fs+quality+source)
		#if Dict[uid] != None:
		#	return MC.message_container('Requested Sources', 'Item already in Requested List')
			
	if mode == common.DOWNLOAD_MODE[1]:
		if file_ext == None:
			file_ext = '.mp4'

		chunk_size = int(1024.0 * 1024.0 * float(common.DOWNLOAD_CHUNK_SIZE)) # in bytes
		fid = '.'+common.id_generator()
		
		EncTxt = E(JSON.StringFromObject({'title':title, 'year':year, 'url':url, 'durl':durl, 'purl':purl, 'sub_url':sub_url, 'summary':summary, 'thumb':thumb, 'fsBytes':int(fsBytes), 'fs':fs, 'chunk_size':chunk_size, 'file_ext':file_ext, 'quality':quality, 'source':source, 'source_meta':source_meta, 'file_meta':file_meta, 'uid':uid, 'fid':fid, 'type':type, 'vidtype':vidtype, 'resumable':resumable, 'status':common.DOWNLOAD_STATUS[4], 'startPos':0, 'timeAdded':time.time(), 'first_time':time.time(), 'progress':0, 'chunk_speed':0,'avg_speed':0,'avg_speed_curr':0, 'eta':0, 'error':'', 'last_error':'Unknown Error', 'action':common.DOWNLOAD_PROPS[3],'section_path':section_path, 'section_title':section_title, 'section_key':section_key, 'user':user})) 
		Dict[uid] = EncTxt
		Dict.Save()
		return MC.message_container('Requested Sources', 'Successfully added to Requested List')
		
	if 'openload' in source.lower() and Prefs['use_openload_pairing'] == False:
		return MC.message_container('Download Sources', 'Use OpenLoad needs to be enabled under Channel Setting/Prefs.')

		
	if tuec not in Dict['DOWNLOAD_OPTIONS_SECTION_TEMP']:
		Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec] = {}
		for x in common.DOWNLOAD_OPTIONS.keys():
			Dict['DOWNLOAD_OPTIONS_SECTION_TEMP'][tuec][x] = common.DOWNLOAD_OPTIONS[x]
		Dict.Save()
		
	return AddToDownloadsList(title=title, purl=purl, url=url, durl=durl, summary=summary, thumb=thumb, year=year, quality=quality, source=source, source_meta=source_meta, file_meta=file_meta, type=type, vidtype=vidtype, resumable=resumable, sub_url=sub_url, fsBytes=fsBytes, fs=fs, file_ext=file_ext, mode=mode, section_path=section_path, section_title=section_title, section_key=section_key, session=session, admin=admin, update=update, user=user,params=params, riptype=riptype)