def __init__(self): threading.Thread.__init__(self, daemon=True) ControllerThread.running = True ControllerThread.autopilot = False self.controller = Settings().get_value(Settings.CONTROLLER) self.vjoy = Settings().get_value(Settings.VJOY_DEVICE) self.axis = Settings().get_value(Settings.STEERING_AXIS)
def __init__(self): self.window = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.window) # Register other windows self.settings_ui = SettingsUI() self.sequence_ui = SequenceUI() self.updater_ui = UpdaterUI() # Define thread variables self.thread_controller = None self.thread_training = None self.thread_autopilot = None self.thread_recording = None # Register buttons and stuff self.ui.actionSettings.triggered.connect(self.settings_ui.show) self.ui.actionExit.triggered.connect(sys.exit) self.ui.actionUpdater.triggered.connect(self.updater_ui.show) self.ui.actionAbout.triggered.connect(self.show_info) self.ui.b_sequenceApply.clicked.connect(self.append_sequence_changes) self.ui.b_sequenceDetails.clicked.connect(self.show_sequence_details) self.ui.b_sequenceDelete.clicked.connect(self.delete_selected_sequence) self.ui.sequence_list.clicked.connect(self.fill_sequence_data_fields) self.ui.b_mode.clicked.connect(self.enter_mode) self.fill_sequence_list() # Try to start controller thread if Settings().get_value(Settings.CONTROLLER) is not None and Settings().get_value(Settings.VJOY_DEVICE) is not None: self.thread_controller = ControllerThread() self.thread_controller.start()
def __init__(self): self.window = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.window) # Register other windows self.settings_ui = SettingsUI() self.updater_ui = UpdaterUI() # Define thread variables self.thread_controller = None self.thread_training = None self.thread_autopilot = None self.thread_recording = None # Register buttons and stuff self.ui.actionSettings.triggered.connect(self.settings_ui.show) self.ui.actionExit.triggered.connect(sys.exit) self.ui.actionUpdater.triggered.connect(self.updater_ui.show) self.ui.actionAbout.triggered.connect(self.show_info) self.ui.b_ets2_vjoy.clicked.connect(self.clicked_ets2_vjoy) self.ui.b_autopilot.clicked.connect(self.clicked_autopilot) # Try to start controller thread if Settings().get_value( Settings.CONTROLLER) is not None and Settings().get_value( Settings.VJOY_DEVICE) is not None: self.thread_controller = ControllerThread() self.thread_controller.start()
def g(tl, text, professional=True, server_side=True): text = clean(text) m = md5.new() m.update('en') m.update(tl) m.update(text) m.update('y') m.update('y') if professional: m.update('speaklikeapi') md5hash = str(m.hexdigest()) t = Cache.getitem('/t/' + md5hash + '/text') if t is not None and len(t) > 1: return t else: speaklikeusername = Settings.get('speaklikeusername') speaklikepw = Settings.get('speaklikepw') speaklikelangs = ['pt', 'ru', 'nl', 'de', 'cs', 'fr', 'it', 'ar', 'ja', 'es', 'zh', 'pl', 'el', 'da'] if tl not in speaklikelangs: professional = False if professional: t = Translation.lucky('en', tl, text, lsp='speaklikeapi', lspusername=SPEAKLIKE_USERNAME, lsppw=SPEAKLIKE_PW, userip=userip) else: t = Translation.lucky('en', tl, text, userip=userip) return t
def __init__(self, statusbar, controller_thread, steering_wheel, image_front): threading.Thread.__init__(self, daemon=True) with AutopilotThread.lock: AutopilotThread.running = True pygame.init() pygame.joystick.init() self.statusbar = statusbar self.controller_thread = controller_thread self.steering_wheel = steering_wheel self.image_front = image_front self.running = True self.country_code = Settings().get_value(Settings.COUNTRY_DEFAULT) self.b_autopilot = Settings().get_value(Settings.AUTOPILOT) self.steering_axis = Settings().get_value(Settings.STEERING_AXIS) self.joystick = pygame.joystick.Joystick(Settings().get_value( Settings.CONTROLLER)) self.joystick.init() self.sess = tf.InteractiveSession(graph=model.g) saver = tf.train.Saver() saver.restore(self.sess, "save/model_%s.ckpt" % self.country_code)
def __init__(self): self.settings = Settings() self.data = Data() country_string = self.settings.get_value(Settings.COUNTRIES_MODEL) countries = country_string.split(",") self.xs = [] self.ys = [] # points to the end of the last batch self.train_batch_pointer = 0 self.val_batch_pointer = 0 # Get all images self.image_list = [] # Workaround self.image_list = self.data.get_image_list_filter(maneuver=0) #for country in countries: # self.image_list += self.data.get_image_list_filter(country=country, maneuver=0) for image in self.image_list: self.steering_deg = float(image[2]) * scipy.pi / 180 # higher steering angles are rare, so add four times # if abs(steering_deg) > 40: # for i in range(int(steering_deg/10-2)*4): # xs.append("../captured/" + line.split()[0]) # ys.append(steering_deg) self.xs.append(os.path.join("captured/", image[1])) # the paper by Nvidia uses the inverse of the turning radius, # but steering wheel angle is proportional to the inverse of turning radius # so the steering wheel angle in radians is used as the output self.ys.append(self.steering_deg) # get number of images self.num_images = len(self.xs) # shuffle list of images self.c = list(zip(self.xs, self.ys)) random.shuffle(self.c) self.xs, self.ys = zip(*self.c) # Training data self.train_xs = self.xs[:int(len(self.xs) * 0.8)] self.train_ys = self.ys[:int(len(self.xs) * 0.8)] # Validation data self.val_xs = self.xs[-int(len(self.xs) * 0.2):] self.val_ys = self.ys[-int(len(self.xs) * 0.2):] self.num_train_images = len(self.train_xs) self.num_val_images = len(self.val_xs) print("Total data:", len(self.xs), self.num_images) print("Training data:", len(self.train_xs)) print("Validation data:", len(self.val_xs))
def requesthandler(self): sl = self.request.get('sl') tl = self.request.get('tl') st = self.request.get('st') domain = self.request.get('domain') url = self.request.get('url') lspusername = Settings.get('speaklike_username') lsppw = Settings.get('speaklike_pw') self.response.out.write(LSP.get(sl, tl, st, domain=domain, url=url, lsp='speaklikeapi', lspusername=lspusername, lsppw=lsppw, worker=True))
def get(self): user = users.get_current_user() if user and users.is_current_user_admin(): name = self.request.get('name') value = self.request.get('value') if len(name) > 0: Settings.save(name, value, user=user.nickname()) self.redirect('/admin/vars') else: self.redirect('/admin')
def __init__(self, statusbar): self.driving_data = DrivingData() with TrainingThread.lock: TrainingThread.running = True threading.Thread.__init__(self, daemon=True) self.statusbar = statusbar country_string = Settings().get_value(Settings.COUNTRIES_MODEL) self.country = country_string.split(",")
def run(self): # Settings instance s = Settings() # State of autopilot self.autopilot = False img_wheel = cv2.imread('steering_wheel_image.jpg', 0) img_wheel = cv2.cvtColor(img_wheel, cv2.COLOR_BGR2RGB) functions.set_image(img_wheel.copy(), self.steering_wheel_ui) rows, cols, _ = img_wheel.shape keyboard.add_hotkey('shift+w', self.hotkey_callback) start_time = functions.current_milli_time() while AutopilotThread.running: self.controller_thread.set_autopilot(self.autopilot) # Get frame of game frame_raw = ImageGrab.grab(bbox=functions.get_screen_bbox()) frame = np.uint8(frame_raw) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Relevant image region for steering angle prediction main = frame[s.get_value(Settings.IMAGE_FRONT_BORDER_TOP):s. get_value(Settings.IMAGE_FRONT_BORDER_BOTTOM), s.get_value(Settings.IMAGE_FRONT_BORDER_LEFT):s. get_value(Settings.IMAGE_FRONT_BORDER_RIGHT)] # Resize the image to the size of the neural network input layer image = scipy.misc.imresize(main, [66, 200]) / 255.0 # Let the neural network predict the new steering angle y_eval = model.y.eval(session=self.sess, feed_dict={ model.x: [image], model.keep_prob: 1.0 })[0][0] degrees = y_eval * 180 / scipy.pi steering = int(round((degrees + 180) / 180 * 32768 / 2)) # Value for vjoy controller # Set the value of the vjoy joystick to the predicted steering angle if self.autopilot: self.controller_thread.set_angle(steering) self.statusbar.showMessage("Autopilot active, steering: " + str(steering)) else: self.statusbar.showMessage("Autopilot inactive") M = cv2.getRotationMatrix2D((cols / 2, rows / 2), -degrees, 1) dst = cv2.warpAffine(img_wheel, M, (cols, rows)) functions.set_image(dst.copy(), self.steering_wheel_ui) functions.set_image(main.copy(), self.image_front_ui) wait_time = functions.current_milli_time() - start_time - 40 if wait_time < 0: time.sleep(-wait_time / 1000) start_time = functions.current_milli_time() keyboard.clear_hotkey('shift+w') self.controller_thread.set_autopilot(False)
def update(language): results = TextObjects.getall() for r in results: translation = LSP.get(sl='en', tl=language, st=r.text, lsp='speaklike',\ lspusername = Settings.get('speaklike_username'),\ lsppw = Settings.get('speaklike_pw'), worker=True) if type(translation) is dict: tt = translation.get('tt', '') elif type(translation) is str: tt = translation else: tt = '' if len(tt) > 0: TextTranslations.save(r.label, tt, language=language, blog=r.blog) return True
def get_screen_bbox(): screen_id = Settings().get_value(Settings.SCREEN) if screen_id is None: screen_id = 0 screen_res = QApplication.desktop().screenGeometry(int(screen_id)) return screen_res.left(), screen_res.top(), screen_res.right( ), screen_res.bottom()
def get(self): if is_admin: self.response.out.write(header()) self.response.out.write('<div class="col1">') self.response.out.write('<h3>Machine Translation Settings</h3>') self.response.out.write('<table>') self.response.out.write('<form action=/admin/mt method=post>') self.response.out.write('<tr><td>Default Translation Engine</td>') self.response.out.write('<input type=hidden name=langpair value=default>') self.response.out.write('<td>' + MT.select() + '</td>') self.response.out.write('</td><td><input type=submit value="Save"></td></tr></form>') self.response.out.write('<tr><td>Google API Key (optional)</td><td>') self.response.out.write('<form action=/admin/mt method=post>') googleapikey = Settings.get('googleapikey') self.response.out.write('<input type=text name=googleapikey value="' + googleapikey + '"></td>') self.response.out.write('<td><input type=submit value="Save"></td></tr></form>') self.response.out.write('<tr><td>WorldLingo Subscription</td><td>') worldlingosubscription = Settings.get('worldlingosubscription') self.response.out.write('<form action=/admin/mt method=post>') self.response.out.write('<input type=text name=worldlingosubscription value="' + worldlingosubscription + '"></td>') self.response.out.write('<td></td></tr>') worldlingopw = Settings.get('worldlingopw') self.response.out.write('<tr><td>WorldLingo password</td>') self.response.out.write('<td><input type=text name=worldlingopw value="' + worldlingopw + '"></td>') self.response.out.write('<td><input type=submit value="Save"></td></tr></form>') self.response.out.write('</table>') self.response.out.write('<hr>') self.response.out.write('<h3>Language Settings</h3>') self.response.out.write('<table>') self.response.out.write('<tr><td>Language Pair</td><td>Translation Engine</td><td></td></tr>') results = MT.find() if len(results) > 0: for r in results: self.response.out.write('<tr><td>' + r.langpair + '</td>') self.response.out.write('<td>' + r.mtengine + '</td>') self.response.out.write('<td><a href=/admin/deletemt?langpair=' + r.langpair + '>Delete</a></td></tr>') self.response.out.write('</table>') self.response.out.write('<h3>Add New Language Pair</h3>') self.response.out.write('<table><form action=/admin/mt method=post>') self.response.out.write('<tr><td>Source Language Code</td><td><input type=text name=sl></td></tr>') self.response.out.write('<tr><td>Target Language Code</td><td><input type=text name=tl></td></tr>') self.response.out.write('<tr><td>Translation Engine</td><td>' + MT.select() + '</td></tr>') self.response.out.write('<tr><td colspan=2><input type=submit value="Save"></td></tr></table></form>') self.response.out.write('</div>') self.response.out.write(footer()) else: self.redirect('/admin')
def fill_screen_list(self): # TODO: SCREEN settings value gets overwritten self.ui.cb_screen.clear() for i in range(len(QApplication.screens())): self.ui.cb_screen.addItem("Screen %d" % (i+1)) screen = Settings().get_value(Settings.SCREEN) if screen is not None: self.ui.cb_screen.setCurrentIndex(int(screen))
def __init__(self, statusbar, controller_thread, image_front): threading.Thread.__init__(self, daemon=True) with AutopilotThread.lock: AutopilotThread.running = True pygame.init() pygame.joystick.init() self.statusbar = statusbar self.controller_thread = controller_thread self.image_front = image_front self.running = True self.country_code = Settings().get_value(Settings.COUNTRY_DEFAULT) self.b_autopilot = Settings().get_value(Settings.AUTOPILOT) self.steering_axis = Settings().get_value(Settings.STEERING_AXIS) self.joystick = pygame.joystick.Joystick(Settings().get_value(Settings.CONTROLLER)) self.joystick.init()
def select_screen(self): screen_id = self.ui.cb_screen.currentIndex() screen_res = QApplication.desktop().screenGeometry(screen_id) Settings().set_value(Settings.SCREEN, screen_id) self.ui.slider_left.setMaximum(screen_res.width()) self.ui.slider_right.setMaximum(screen_res.width()) self.ui.slider_top.setMaximum(screen_res.height()) self.ui.slider_bottom.setMaximum(screen_res.height())
def fill_device_list(self): self.ui.cb_devices.clear() joystick_count = 0 if joystick_count > 0: for i in range(joystick_count): self.ui.cb_devices.addItem('None') device = Settings().get_value(Settings.CONTROLLER) if device is not None and int(device) < joystick_count: self.ui.cb_devices.setCurrentIndex(int(device))
def fill_device_list(self): if pygame.joystick.get_init(): pygame.joystick.quit() pygame.joystick.init() self.ui.cb_devices.clear() joystick_count = pygame.joystick.get_count() if joystick_count > 0: for i in range(joystick_count): self.ui.cb_devices.addItem(pygame.joystick.Joystick(i).get_name()) device = Settings().get_value(Settings.CONTROLLER) if device is not None and int(device) < joystick_count: self.ui.cb_devices.setCurrentIndex(int(device))
def __init__(self, statusbar, image_front, fill_sequence_list): threading.Thread.__init__(self, daemon=True) with RecordingThread.lock: RecordingThread.running = True self.statusbar = statusbar self.image_front = image_front self.running = True self.joystick = pygame.joystick.Joystick(Settings().get_value(Settings.CONTROLLER)) self.fill_sequence_list = fill_sequence_list if not os.path.exists("captured/"): os.mkdir("captured")
def get(self): if is_admin(): self.response.out.write(header()) self.response.out.write('<div class="col1">') self.response.out.write('<h2>Worldwide Lexicon Quick Setup</h2>') self.response.out.write('<table><form action=/admin/setup method=post>') title = Settings.get('title') if len(title) < 1: title = 'Worldwide Lexicon Server' self.response.out.write('<tr><td>Website Title</td><td><input type=text name=title value="' + title + '"></td></tr>') self.response.out.write('<tr><td>Root URL</td><td><input type=text name=root_url value="' + Settings.get('root_url') + '"></td></tr>') primary_language = Settings.get('primary_language') if len(primary_language) < 1: primary_language = 'en' self.response.out.write('<tr><td>Primary Language</td><td><select name=primary_language>' + languages.select(selected=primary_language) + '</select></td></tr>') self.response.out.write('<tr><td><a href=http://www.akismet.com>Akismet</a> Anti-Spam Key</td><td><input type=text name=akismet value="' + Settings.get('akismet') + '"></td></tr>') self.response.out.write('<tr><td><a href=http://www.maxmind.com>Maxmind Geolocation</a> Key</td><td><input type=text name=maxmind value="' + Settings.get('maxmind') + '"></td></tr>') self.response.out.write('<tr><td><a href=http://www.google.com/analytics>Google Analytics</a> Key</td><td><input type=text name=googleanalytics value="' + Settings.get('googleanalytics') + '"></td></tr>') self.response.out.write('<tr><td colspan=2><input type=submit value="Save"></td></tr>') self.response.out.write('</table></form>') self.response.out.write('</div>') self.response.out.write(footer()) else: self.redirect('/admin')
def read(subreddit): api = httplib.get_json( 'https://www.reddit.com/r/{0}.json?limit={1}'.format( subreddit, Settings.get('max_results'))) data = [x['data'] for x in api['data']['children']] if data: results = {} for item in data: if not item['stickied']: results[item['title']] = { 'url': item['url'], 'score': item['score'], 'ups': item['ups'], 'downs': item['downs'], 'comments': item['num_comments'] } return results else: return False
def query(remote_addr, website=''): """ Queries the Maxmind geolocation service to obtain a location fix for an IP address. """ license_key=Settings.get('maxmind') location = dict() geolist=list() location['country']='' location['state']='' location['city']='' location['latitude']=None location['longitude']=None if len(remote_addr) > 4 and license_key is not None: url = 'http://geoip1.maxmind.com/b?l=' + license_key + '&i=' + remote_addr try: result=urlfetch.fetch(url) if result.status_code == 200: geo = result.content except: geo = '' else: geo = '' if len(geo) > 1: geolist = string.split(geo,',') if len(geolist) > 0: ctr=0 for i in geolist: if ctr==0: location['country']=i elif ctr==1: location['state']=i elif ctr==2: location['city']=i elif ctr==3: if len(i) > 0: location['latitude']=float(i) elif ctr==4: if len(i) > 0: location['longitude']=float(i) ctr=ctr+1 return location
def lookup(cookies): cookie = facebook.get_user_from_cookie(cookies, Settings.get('facebook_app_id'), Settings.get('facebook_app_secret')) if cookie: # Store a local instance of the user data so we don't need # a round-trip to Facebook on every request user = FBUser.get_by_key_name(cookie["uid"]) if not user: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") user = FBUser(key_name=str(profile["id"]), id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=cookie["access_token"]) user.put() elif user.access_token != cookie["access_token"]: user.access_token = cookie["access_token"] user.put() return profile else: return
def post(self): if is_admin: googleapikey = self.request.get('googleapikey') worldlingosubscription = self.request.get('worldlingosubscription') worldlingopw = self.request.get('worldlingopw') sl = self.request.get('sl') tl = self.request.get('tl') langpair = self.request.get('langpair') mtengine = self.request.get('mtengine') if len(googleapikey) > 0: Settings.set('googleapikey', googleapikey) elif len(worldlingosubscription) > 0 and len(worldlingopw) > 0: Settings.set('worldlingosubscription', worldlingosubscription) Settings.set('worldlingopw', worldlingopw) elif len(sl) > 0 and len(tl) > 0 and len(mtengine) > 0: MT.add(sl, tl, mtengine) elif langpair == 'default': MT.add(langpair,langpair,mtengine) self.redirect('/admin/mt') else: self.redirect('/admin')
def post(self): if is_admin(): title = self.request.get('title') root_url = self.request.get('root_url') primary_language = self.request.get('primary_language') akismet = self.request.get('akismet') maxmind = self.request.get('maxmind') googleanalytics = self.request.get('googleanalytics') if len(title) > 0: Settings.save('title', title) if len(root_url) > 0: if string.count(root_url, 'http://') < 1: root_url = 'http://' + root_url Settings.save('root_url', root_url) if len(primary_language) > 1: Settings.save('primary_language', primary_language) if len(akismet) > 1: Settings.save('akismet', akismet) if len(maxmind) > 1: Settings.save('maxmind', maxmind) if len(googleanalytics) > 1: Settings.save('googleanalytics', googleanalytics) self.redirect('/admin/setup') else: self.redirect('/admin')
sdb = db.Query(Score) results = sdb.fetch(limit=250) if len(results) > 0: db.delete(results) tdb = db.Query(Translation) tdb.filter('scores > ', 0) results = tdb.fetch(limit=250) for r in results: r.scores = 0 r.rawscore = 0 r.userscores = 0 r.userrawscore = 0 r.put() self.response.out.write('ok') debug_setting = Settings.get('debug') if debug_setting == 'True': debug_setting = True elif debug_setting == 'False': debug_setting = False else: debug_setting = True application = webapp.WSGIApplication([('/scores/get', GetScores), ('/scores/lsp', LSPScore), ('/scores/reset', ResetScores), ('/scores/vote', SaveScore), ('/scores/user', SetUserScores)], debug=debug_setting) def main():
def read(subreddit): api = httplib.get_json('https://www.reddit.com/r/{0}.json?limit={1}'.format(subreddit, Settings.get('max_results'))) data = [x['data'] for x in api['data']['children']] if data: results = {} for item in data: if not item['stickied']: results[item['title']] = {'url':item['url'], 'score':item['score'], 'ups':item['ups'], 'downs':item['downs'], 'comments':item['num_comments']} return results else: return False
def run(self): # Settings instance s = Settings() # State of autopilot autopilot = False # Previous state of the autopilot button autopilot_button_prev = 0 # Previous value of steering (gamepad) manual_steering_prev = 0 while AutopilotThread.running: pygame.event.pump() # Button to activate/deactivate autopilot autopilot_button_act = self.joystick.get_button(self.b_autopilot) # Button was pressed if autopilot_button_act != autopilot_button_prev and autopilot_button_act == 1: autopilot = not autopilot # if autopilot and settings.AUTOPILOT_SOUND_ACTIVATE: # autopilot_engage.play() autopilot_button_prev = autopilot_button_act # Read the steering value of joystick axis = round((self.joystick.get_axis(self.steering_axis) + 1) * 32768 / 2) # Interrupt autopilot if manual steering was detected if abs(manual_steering_prev - axis) > 1000 and autopilot: self.controller_thread.set_autopilot(False) autopilot = False manual_steering_prev = axis self.controller_thread.set_autopilot(autopilot) # Get frame of game frame_raw = ImageGrab.grab(bbox=functions.get_screen_bbox()) frame = np.uint8(frame_raw) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Relevant image region for steering angle prediction main = frame[s.get_value(Settings.IMAGE_FRONT_BORDER_TOP):s.get_value(Settings.IMAGE_FRONT_BORDER_BOTTOM), s.get_value(Settings.IMAGE_FRONT_BORDER_LEFT):s.get_value(Settings.IMAGE_FRONT_BORDER_RIGHT)] # Resize the image to the size of the neural network input layer image = scipy.misc.imresize(main, [66, 200]) / 255.0 ### Detect lane and steer ### # Do a perspective transformation of the lane. M, Minv = get_perspective_transform_matrix(main, 1, 0.2, 0.4, 0, [300, 300]) image_warped = cv2.warpPerspective(main.copy(), M, (300, 300), flags=cv2.INTER_LINEAR) # Filter lane markings. lower_white = np.array([180, 180, 180]) upper_white = np.array([255, 255, 255]) mask = cv2.inRange(image_warped, lower_white, upper_white) image_warped_filtered = cv2.bitwise_and(image_warped, image_warped, mask=mask) _, image_warped_filtered_binary = cv2.threshold(image_warped_filtered, 1, 255, cv2.THRESH_BINARY) # # Find position of left and right markings. # histogram = generate_column_histogram(image_warped_filtered_binary) # left_markings = histogram.index(max(histogram[:150])) # right_markings = histogram.index(max(histogram[150:])) # log.debug((left_markings, right_markings)) window_width = 75 window_height = 50 # First half (left markings) column_count = int(image_warped_filtered_binary.shape[1]/window_width) left_prediction = [] right_prediction = [] for column in range(0, int(column_count/2)): left_predicted_center = int(window_width/2 + column*window_width) left_prediction.append(get_centered_sliding_window(image_warped_filtered_binary, left_predicted_center, window_width, window_height)) right_predicted_center = int(window_width / 2 + (column + column_count/2) * window_width) right_prediction.append(get_centered_sliding_window(image_warped_filtered_binary, right_predicted_center, window_width, window_height)) # Select the sector with the highest maximum. left_markings_histogram_max = [x[2] for x in left_prediction] left_markings_center = [x[1] for x in left_prediction] left_markings = left_markings_center[left_markings_histogram_max.index(max(left_markings_histogram_max))] right_markings_histogram_max = [x[2] for x in right_prediction] right_markings_center = [x[1] for x in right_prediction] right_markings = right_markings_center[right_markings_histogram_max.index(max(right_markings_histogram_max))] log.debug(('LEFT', left_markings_center, left_markings_histogram_max)) log.debug(('RIGHT', right_markings_center, right_markings_histogram_max)) log.debug(('CHOSE', left_markings, right_markings)) left_centers = [None] right_centers = [None] if left_markings > 0 and right_markings > 0: # Apply sliding window technique. window_count = int(image_warped_filtered_binary.shape[0]/window_height) left_centers = [left_markings] right_centers = [right_markings] # Go through all rows (from bottom to top of the image). for row in range(1, window_count): if row > 0: last_value = row-1 else: last_value = 0 # Take the center (global position) of the last row and use it as entry point. # Then look window_width/2 to the left and to the right and determine the more precise # center in that area. _, corrected_center_left, _ = get_centered_sliding_window(image_warped_filtered_binary, left_centers[last_value], window_width, window_height, row) _, corrected_center_right, _ = get_centered_sliding_window(image_warped_filtered_binary, right_centers[last_value], window_width, window_height, row) if row == 0: left_centers = [] right_centers = [] left_centers.append(corrected_center_left) right_centers.append(corrected_center_right) log.debug(('LEFT_CENTERS', left_centers)) log.debug(('RIGHT_CENTERS', right_centers)) lane_final_image = image_warped_filtered_binary.copy() if left_centers[0]: lane_final_image = cv2.line(lane_final_image, (left_centers[0], 0), (left_centers[0], 300), (255, 0, 0), 5) if right_centers[0]: lane_final_image = cv2.line(lane_final_image, (right_centers[0], 0), (right_centers[0], 300), (0, 255, 0), 5) # TODO: Determine center of lane and calculate degrees to reach this center. y_eval = 0 degrees = y_eval * 180 / scipy.pi steering = int(round((degrees + 180) / 180 * 32768 / 2)) # Value for vjoy controller # Set the value of the vjoy joystick to the predicted steering angle if autopilot: self.controller_thread.set_angle(steering) self.statusbar.showMessage("Autopilot active") else: self.statusbar.showMessage("Autopilot inactive") # functions.set_image(main.copy(), self.image_front) functions.set_image(lane_final_image.copy(), self.image_front)
def current_user(self): if not hasattr(self, "_current_user"): self._current_user = None cookie = facebook.get_user_from_cookie( self.request.cookies, Settings.get('facebook_app_id'), Settings.get('facebook_app_secret')) if cookie: # Store a local instance of the user data so we don't need # a round-trip to Facebook on every request user = User.get_by_key_name(cookie["uid"]) if not user: location = geolocate(self.request.remote_addr) localelist = string.split(self.request.headers['Accept-Language'],',') locales = list() for l in localelist: langloc = string.split(l, ';') locales.append(langloc[0]) if location is not None: city = location.get('city','') country = location.get('country','') try: latitude = float(location.get('latitude','')) longitude = float(location.get('longitude','')) except: latitude = None longitude = None graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") if latitude is not None: user = User(key_name=str(profile["id"]), id=str(profile["id"]), name=profile["name"], gender=profile['gender'], city=city, country=country, latitude=latitude, longitude=longitude, locale = profile["locale"], locales = locales, profile_url=profile["link"], access_token=cookie["access_token"]) else: user = User(key_name=str(profile["id"]), id=str(profile["id"]), name=profile["name"], gender=profile['gender'], city=city, country=country, locale = profile["locale"], locales = locales, profile_url=profile["link"], access_token=cookie["access_token"]) user.put() p=dict() p['name']=profile['name'] p['city']=city p['country']=country p['locale']=profile['locale'] taskqueue.add(url='/wwl/userstatsworker', queue_name='counter', params=p) elif user.access_token != cookie["access_token"]: user.access_token = cookie["access_token"] user.put() self._current_user = user return self._current_user
def run(self): s = Settings() d = Data(batch=True) img_id = d.get_next_fileid() recording = False recording_button_prev = 0 maneuver = 0 # 0 - normal, 1 - indicator left, 2 - indicator right indicator_left = False indicator_left_prev = 0 indicator_right = False indicator_right_prev = 0 last_record = 0 while RecordingThread.running: pygame.event.pump() recording_button_act = self.joystick.get_button(s.get_value(Settings.AUTOPILOT)) if recording_button_act != recording_button_prev and recording_button_act == 1: recording = not recording if recording: # started recording sequence_id = d.add_sequence() else: # stopped recording self.fill_sequence_list() recording_button_prev = recording_button_act indicator_left_act = self.joystick.get_button(s.get_value(Settings.LEFT_INDICATOR)) if indicator_left_act != indicator_left_prev and indicator_left_act == 1: indicator_left = not indicator_left # Switch indicator if indicator_left and indicator_right: indicator_right = False indicator_left_prev = indicator_left_act indicator_right_act = self.joystick.get_button(s.get_value(Settings.RIGHT_INDICATOR)) if indicator_right_act != indicator_right_prev and indicator_right_act == 1: indicator_right = not indicator_right # Switch indicator if indicator_right and indicator_left: indicator_left = False indicator_right_prev = indicator_right_act if indicator_left: maneuver = 1 elif indicator_right: maneuver = 2 else: maneuver = 0 if recording: self.statusbar.showMessage("Recording: active | Indicator: %s" % functions.get_indicator(maneuver)) else: self.statusbar.showMessage("Recording: inactive | Indicator: %s" % functions.get_indicator(maneuver)) # Capture the whole game frame_raw = ImageGrab.grab(bbox=functions.get_screen_bbox()) frame = np.uint8(frame_raw) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) main = frame[s.get_value(Settings.IMAGE_FRONT_BORDER_TOP):s.get_value(Settings.IMAGE_FRONT_BORDER_BOTTOM), s.get_value(Settings.IMAGE_FRONT_BORDER_LEFT): s.get_value(Settings.IMAGE_FRONT_BORDER_RIGHT)] # gray = cv2.cvtColor(main, cv2.COLOR_BGR2GRAY) # blur_gray = cv2.GaussianBlur(gray, (3, 3), 0) # edges = cv2.Canny(blur_gray, 50, 150) # dilated = cv2.dilate(edges, (3,3), iterations=2) # Resize image to save some space (height = 100px) ratio = main.shape[1] / main.shape[0] resized = cv2.resize(main, (round(ratio * 100), 100)) # cv2.imshow('cap', dilated) # cv2.imshow('resized', resized) functions.set_image(main.copy(), self.image_front) axis = self.joystick.get_axis(s.get_value(Settings.STEERING_AXIS)) * 180 # -180 to 180 "degrees" throttle = self.joystick.get_axis(s.get_value(Settings.THROTTLE_AXIS)) * 100 # -100=full throttle, 100=full brake speed = speed_detection.get_speed(frame) # Save frame every 150ms if recording and (functions.current_milli_time() - last_record) >= 150: last_record = functions.current_milli_time() cv2.imwrite("captured/%d.png" % img_id, resized) d.add_image("%d.png" % img_id, axis, speed, throttle, maneuver, sequence_id) img_id += 1 d.append()
def create(): # Get player id stored in a cookie player_id = request.cookies.get('uuid') # List of all players on the website player = Player.query.filter_by(uuid=player_id).first() # If user doesnt have a name and id assigned, redirect them to create one if not player_id or not player: return redirect('/name/create') if request.method == 'POST': # User has not accepted the use of cookies if not request.cookies.get('cookies'): return render_template( 'create.html', settings=settings_values, error='You must accept the use of cookies before proceeding.') # Validate recaptcha if not recaptcha.verify(): return render_template('create.html', settings=settings_values, error='ReCaptcha failed.') difficulty = Difficulty.query.filter_by( name=request.form.get('difficulty')).first() goal = Goal.query.filter_by(name=request.form.get('goal')).first() logic = Logic.query.filter_by(name=request.form.get('logic')).first() mode = Mode.query.filter_by(name=request.form.get('mode')).first() variation = Variation.query.filter_by( name=request.form.get('variation')).first() weapons = Weapons.query.filter_by( name=request.form.get('weapons')).first() settings = Settings(difficulty, bool(request.form.get('enemizer')), goal, logic, mode, bool(request.form.get('spoilers')), bool(request.form.get('tournament')), variation, weapons) settings_validate, settings_error = validation.validate_settings( settings) # Make certain that all selected settings exist if not settings_validate: return render_template('create.html', settings=settings, error=settings_error) seed = alttpr_api.generate_seed(settings.to_dict()) hash_code = seed['hash'] chat_url = chat.get_chat_room(hash_code) # Create a game room room = Room(settings=settings, chat_url=chat_url, creator=player, hash_code=hash_code) #db.session.add(settings) db.session.add(room) db.session.commit() # generate response that redirects to the game room just created response = make_response(redirect(f'/room/{room.hash_code}')) return response else: return render_template('create.html', settings=settings_values, error=None)
def get(self, p1='', p2='', p3=''): slu = Settings.get('speaklikeusername') slp = Settings.get('speaklikepw') try: locales = string.split(self.request.headers['Accept-Language'],',') except: locales = 'en-us' found_locale = False language = '' locale = '' for l in locales: langloc = string.split(l, '-') if len(language) < 1: language = langloc[0] if not found_locale: f = FBLocales() locale = f.lookup(langloc[0]) if locale is not None: if len(locale) > 1: found_locale=True if not found_locale: locale = 'en_US' if len(language) < 1: language = 'en' dmenus = '<ul><li><a href=http://www.worldwidelexicon.org>Worldwide Lexicon</a></li>\ <li><a href=http://www.worldwidelexicon.org>' + g(language,clean('Tools For Webmasters')) + '</a></li></ul>' if len(language) > 2: language = language[0:2] proxy_settings = '<meta name="allow_edit" content="y" />' lsp = '' lspusername = '' lsppw = '' userip = self.request.remote_addr headers = self.request.headers host = headers.get('host','') if p1 == 'blog': self.redirect('http://blog.worldwidelexicon.org') elif host == 'www.worldwidelexicon.org': self.redirect('http://www.worldwidelexicon.org/home') elif p1 == 's': self.error(404) self.response.out.write('<h2>Page Not Found</h2>') else: w = web() w.get(template) w.replace(template,'[social_translation]', clean(g(language,'Social Translation'))) t = '' t = t + clean(g(language, 'Machine translation is great, but we all know it often produces inaccurate (and sometimes funny) translations. ')) t = t + clean(g(language, 'Der Mundo is the worldwide web, translated by people. We use machine translation (from Google Translate and Apertium) to produce a rough draft. ')) t = t + clean(g(language, 'Then users take over to edit the translations, score translations from other users, and make them better.<p>')) w.replace(template, '[introduction]', t) t = '<p><table><form action=/translate/project method=get>' t = t + '</select></td></tr>' t = t + '<tr><td>URL</td><td><input type=text size=40 name=u value="http://www.aljazeera.net"></td></tr>' # t = t + '<tr><td>Require encryption</td><td><input type=checkbox value=y name=secure></td></tr>' t = t + '<tr><td colspan=2>' + g(language, 'Optional professional translation by <a href=http://www.speaklike.com>SpeakLike</a>') + '</td></tr>' t = t + '<tr><td>SpeakLike username</td><td><input type=text name=lspusername></td></tr>' t = t + '<tr><td>SpeakLike password</td><td><input type=password name=lsppw></td></tr>' t = t + '<tr><td></td><td>' t = t + ' ' + g(language,'Professional translations are usually completed within 24 hours.') t = t + ' ' + g(language,'We will provide a temporary machine translation until then.') t = t + ' ' + g(language,'When completed, professional translations will be visible to other users.') t = t + '</td></tr>' t = t + '<tr><td colspan=2><input type=submit value="' + g(language, 'Translate!', server_side=True) + '"></td></tr>' t = t + '</form></table><p>' w.replace(template,'[start_form]',t) w.replace(template,'[google_analytics]',google_analytics_header) w.replace(template,'[title]','Der Mundo : ' + g(language,'Translate the world with your friends', server_side=True)) w.replace(template,'[meta]', sharethis_header + snapshot_code) w.replace(template,'[copyright]',standard_footer) w.replace(template,'[menu]',dmenus) w.replace(template,'[about]', g(language,'About')) w.replace(template,'[tagline]', g(language, 'Translate the world with your friends')) w.replace(template,'[share_this_page]', g(language, 'Share This Page')) w.replace(template,'[share_this_button]', sharethis_button) w.replace(template,'[instructions]', g(language, 'Instructions')) w.replace(template,'[instructions_prompt]', g(language, instructions)) w.replace(template,'[language]', language) w.replace(template,'[wordpress]', g(language, wordpress)) w.replace(template,'[wordpress_prompt]', g(language, wordpress_prompt)) w.replace(template,'[firefox]', g(language, firefox)) w.replace(template,'[firefox_prompt]', g(language,firefox_prompt)) text = """<div id="fb-root"></div> <script src="http://connect.facebook.net/""" + locale + """/all.js"></script> <script> FB.init({ appId : '140342715320', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); </script> <fb:login-button autologoutlink="true" width="200">Login with Facebook</fb:login-button>""" user = FBUser.lookup(self.request.cookies, self.request.remote_addr) #if user is not None: # text = text + '<p><a href=' + user.get('profile_url','') + '><img src=http://graph.facebook.com/' + user.get('id ','')+ '/picture?type=square/></a></p>' text = text + """ """ w.replace(template,'[facebook_login]',text) text = '<fb:like show_faces="true" width="450"></fb:like><br>' w.replace(template,'[facebook_like]',text) Cache.setitem('/dermundo/cache/' + language, w.out(template), 600) self.response.out.write(w.out(template))
from language import TestLanguage from transcoder import transcoder from webappcookie import Cookies from wwlgae import wwl from www import web from www import www from shorturl import UrlEncoder from BeautifulSoup import BeautifulSoup from excerpt_extractor import get_summary import sgmllib template = 'http://www.dermundo.com/css/template.css' usertemplate = 'http://www.dermundo.com/dermundocss/profile.html' sidebar_url = 'http://www.dermundo.com/dermundocss/sidebar.html' FACEBOOK_APP_ID = Settings.get('facebook_app_id') FACEBOOK_APP_SECRET = Settings.get('facebook_app_secret') SPEAKLIKE_USERNAME = Settings.get('speaklike_username') SPEAKLIKE_PW = Settings.get('speaklike_pw') userip ='' # Define convenience functions def clean(text): return transcoder.clean(text) def pro(tl, text): return g(tl, text, professional=True)
def _load_settings(self): settings = Settings() # Screen data image_front_border_left = settings.get_value(settings.IMAGE_FRONT_BORDER_LEFT) image_front_border_right = settings.get_value(settings.IMAGE_FRONT_BORDER_RIGHT) image_front_border_top = settings.get_value(settings.IMAGE_FRONT_BORDER_TOP) image_front_border_bottom = settings.get_value(settings.IMAGE_FRONT_BORDER_BOTTOM) # Controller binding vjoy = settings.get_value(settings.VJOY_DEVICE) autopilot = settings.get_value(settings.AUTOPILOT) left_indicator = settings.get_value(settings.LEFT_INDICATOR) right_indicator = settings.get_value(settings.RIGHT_INDICATOR) steering_axis = settings.get_value(settings.STEERING_AXIS) throttle_axis = settings.get_value(settings.THROTTLE_AXIS) self.fill_screen_list() self.fill_device_list() self.select_screen() # Set scrollbar values if image_front_border_right is not None: self.ui.slider_right.setValue(int(image_front_border_right)) else: self.ui.slider_right.setValue(self.ui.slider_right.maximum()) if image_front_border_left is not None: self.ui.slider_left.setValue(int(image_front_border_left)) else: self.ui.slider_left.setValue(self.ui.slider_left.minimum()) if image_front_border_bottom is not None: self.ui.slider_bottom.setValue(int(image_front_border_bottom)) else: self.ui.slider_bottom.setValue(self.ui.slider_bottom.maximum()) if image_front_border_top is not None: self.ui.slider_top.setValue(int(image_front_border_top)) else: self.ui.slider_top.setValue(self.ui.slider_top.minimum()) # Display key bindings if vjoy is not None: self.ui.e_vjoy.setText(str(vjoy)) if autopilot is not None: self.ui.e_autopilot.setText(str(autopilot)) if left_indicator is not None: self.ui.e_leftIndicator.setText(str(left_indicator)) if right_indicator is not None: self.ui.e_rightIndicator.setText(str(right_indicator)) if steering_axis is not None: self.ui.e_steering.setText(str(steering_axis)) if throttle_axis is not None: self.ui.e_throttle.setText(str(throttle_axis)) self.fill_screen_cap()
def save_settings(self): settings = Settings() settings.set_value(settings.IMAGE_FRONT_BORDER_LEFT, self.ui.slider_left.value()) settings.set_value(settings.IMAGE_FRONT_BORDER_RIGHT, self.ui.slider_right.value()) settings.set_value(settings.IMAGE_FRONT_BORDER_TOP, self.ui.slider_top.value()) settings.set_value(settings.IMAGE_FRONT_BORDER_BOTTOM, self.ui.slider_bottom.value()) settings.set_value(settings.SCREEN, self.ui.cb_screen.currentIndex()) settings.set_value(settings.CONTROLLER, self.ui.cb_devices.currentIndex()) settings.set_value(settings.VJOY_DEVICE, self.ui.e_vjoy.text()) settings.set_value(settings.AUTOPILOT, self.ui.e_autopilot.text()) settings.set_value(settings.LEFT_INDICATOR, self.ui.e_leftIndicator.text()) settings.set_value(settings.RIGHT_INDICATOR, self.ui.e_rightIndicator.text()) settings.set_value(settings.STEERING_AXIS, self.ui.e_steering.text()) settings.set_value(settings.THROTTLE_AXIS, self.ui.e_throttle.text()) self.hide()
def get(self): self.response.out.write(Settings.get('status'))
css_wide = '<div id="left">' css_wide_close = '</div>' css_sidebar = '<div id="right"><div class="box">' css_sidebar_close = '</div></div>' css_footer = '<div id="clear"></div></div><div id="footer">(c) 2008-2010 Worldwide Lexicon Inc, (c) 1998-2010, Brian S McConnell</div></div>' # Google Analytics Header google_analytics_header = '<script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");\ document.write(unescape("%3Cscript src=\'\" + gaJsHost + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));\ </script>\ <script type="text/javascript">\ try {\ var pageTracker = _gat._getTracker("' + Settings.get('googleanalytics') + '");\ pageTracker._trackPageview();\ } catch(err) {}</script>' sidebar_about = '<h3>About WWL</h3>\ The Worldwide Lexicon is an open source collaborative translation platform. It is similar to \ systems like <a href=http://www.wikipedia.org>Wikipedia</a>, and combines machine translation \ with submissions from volunteers and professional translators. WWL is a translation memory, \ essentially a giant database of translations, which can be embedded in almost any website or \ web application.<br><br>\ Our mission is to eliminate the language barrier for interesting websites and articles, by \ enabling people to create translation communities around their favorite webites, topics or \ groups.<br><br>\ WWL is open source software, published under the New BSD license, and can be adapted for \ commercial and non-commercial use, and can be customized for a wide variety of applications, \
def run(self): s = Settings() d = Data(batch=True) img_id = d.get_next_fileid() self.recording = False maneuver = 0 # 0 - normal, 1 - indicator left, 2 - indicator right last_record = functions.current_milli_time() keyboard.add_hotkey('shift+w', self.record_callback, args=[d]) while RecordingThread.running: # Capture the whole game frame_raw = ImageGrab.grab(bbox=functions.get_screen_bbox()) frame = np.uint8(frame_raw) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) main = frame[s.get_value(Settings.IMAGE_FRONT_BORDER_TOP):s. get_value(Settings.IMAGE_FRONT_BORDER_BOTTOM), s.get_value(Settings.IMAGE_FRONT_BORDER_LEFT):s. get_value(Settings.IMAGE_FRONT_BORDER_RIGHT)] # gray = cv2.cvtColor(main, cv2.COLOR_BGR2GRAY) # blur_gray = cv2.GaussianBlur(gray, (3, 3), 0) # edges = cv2.Canny(blur_gray, 50, 150) # dilated = cv2.dilate(edges, (3,3), iterations=2) # Resize image to save some space (height = 100px) ratio = main.shape[1] / main.shape[0] resized = cv2.resize(main, (round(ratio * 100), 100)) # cv2.imshow('cap', dilated) # cv2.imshow('resized', resized) functions.set_image(main.copy(), self.image_front) axis, throttle, speed = get_steering_throttle_speed() if axis == 0: maneuver = 0 elif axis > 0: maneuver = 1 else: maneuver = 2 if self.recording: self.statusbar.showMessage( "Recording: active | Indicator: %s" % functions.get_indicator(maneuver)) else: self.statusbar.showMessage( "Recording: inactive | Indicator: %s" % functions.get_indicator(maneuver)) # Save frame every 150ms if self.recording: cv2.imwrite("captured/%d.png" % img_id, resized) d.add_image("%d.png" % img_id, axis, speed, throttle, maneuver, self.sequence_id) img_id += 1 # at least wait 150ms wait_milli_time = functions.current_milli_time( ) - last_record - 150 if wait_milli_time < 0: time.sleep(-wait_milli_time / 1000) last_record = functions.current_milli_time() else: time.sleep(0.15) keyboard.clear_hotkey('shift+w') d.append()
def requesthandler(self): guid = self.request.get('guid') cl = self.request.get('cl') comment = clean(self.request.get('comment')) if len(cl) < 1 and len(comment) > 4: cl = TestLanguage.language(text=comment) remote_addr = self.request.remote_addr ip = self.request.get('ip') if len(ip) > 0: remote_addr = ip username = self.request.get('username') pw = self.request.get('pw') session='' location = geo.get(remote_addr) if type(location) is dict: try: city = location['city'] state= location['state'] country= location['country'] except: city = '' state = '' country = '' try: latitude=location['latitude'] longitude=location['longitude'] except: latitude = None longitude = None if len(comment) > 5 and len(guid) > 7: emptyform=False else: emptyform=True if not emptyform: spamchecked = False akismetkey = Settings.get('akismet') root_url = Settings.get('root_url') if len(root_url) > 0 and string.count(root_url, 'http://') < 1: root_url = 'http://' + root_url a = Akismet() a.setAPIKey(akismetkey, blog_url = root_url) if a.verify_key(): data = dict() data['user_ip']=remote_addr data['user_agent']=self.request.headers['User-Agent'] if a.comment_check(comment, data): spam=True else: spam=False spamchecked=True else: spam=False spamchecked=False result = False if len(username) > 0: session = Users.auth(username=username, pw=pw, session='') if len(session) < 8: username='' if not spam: tdb = db.Query(Translation) tdb.filter('guid = ', guid) item = tdb.get() if item is not None: md5hash = item.md5hash sl = item.sl tl = item.tl st = item.st tt = item.tt domain = item.domain url = item.url professional = item.professional author = item.username cdb = db.Query(Comment) cdb.filter('guid = ', guid) cdb.filter('remote_addr = ', remote_addr) item = cdb.get() if item is None: item = Comment() item.guid = guid item.md5hash = md5hash item.tl = tl item.cl = cl item.comment = comment item.username = username item.spamchecked = spamchecked item.spam = spam item.remote_addr = remote_addr timestamp = datetime.datetime.now() item.minute = timestamp.minute item.hour = timestamp.hour item.day = timestamp.day item.month = timestamp.month item.year = timestamp.year item.domain = domain item.url = url item.city = city item.state = state item.country = country try: item.latitude = latitude item.longitude = longitude except: pass item.put() if professional and len(author) > 0: LSP.comment(guid, comment, lsp=author, username=username, remote_addr=remote_addr) result = True self.response.headers['Content-Type']='text/plain' if result: self.response.out.write('ok') else: self.error(500) self.response.out.write('error') else: tdb = db.Query(Translation) tdb.order('-date') item = tdb.get() if item is not None: guid = item.guid else: guid = '' t = '<table><form action=/comments/submit method=post accept-charset=utf-8>' t = t + '<tr><td>GUID of Translation (guid)</td><td><input type=text name=guid value="' + guid + '"></td></tr>' t = t + '<tr><td>Comment (comment)</td<td><input type=text name=comment></td></tr>' t = t + '<tr><td>Username (username, optional)</td><td><input type=text name=username></td></tr>' t = t + '<tr><td>Password (pw, optional)</td><td><input type=text name=pw></td></tr>' t = t + '<tr><td colspan=2><input type=submit value=SUBMIT></td></tr></table></form>' www.serve(self,t,sidebar=self.__doc__, title = '/comments/submit')
def run(self): # Settings instance s = Settings() # State of autopilot autopilot = False # Previous state of the autopilot button autopilot_button_prev = 0 # Previous value of steering (gamepad) manual_steering_prev = 0 img_wheel = cv2.imread('steering_wheel_image.jpg', 0) rows, cols = img_wheel.shape while AutopilotThread.running: pygame.event.pump() # Button to activate/deactivate autopilot autopilot_button_act = self.joystick.get_button(self.b_autopilot) # Button was pressed if autopilot_button_act != autopilot_button_prev and autopilot_button_act == 1: autopilot = not autopilot #if autopilot and settings.AUTOPILOT_SOUND_ACTIVATE: # autopilot_engage.play() autopilot_button_prev = autopilot_button_act # Read the steering value of joystick axis = round( (self.joystick.get_axis(self.steering_axis) + 1) * 32768 / 2) # Interrupt autopilot if manual steering was detected if abs(manual_steering_prev - axis) > 500 and autopilot: img_id = Data().get_next_fileid() sequence_id = Data().add_sequence(country=Settings().get_value( Settings.COUNTRY_DEFAULT), note="correction") self.controller_thread.set_autopilot(False) self.statusbar.showMessage("Autopilot inactive") # TODO: Deactivate this feature in settings # TODO: Amount of images to save in settings # Save the next 3 images for i in range(3): # Get frame of game frame_raw = ImageGrab.grab( bbox=functions.get_screen_bbox()) frame = np.uint8(frame_raw) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Relevant image region for steering angle prediction main = frame[ s.get_value(Settings.IMAGE_FRONT_BORDER_TOP):s. get_value(Settings.IMAGE_FRONT_BORDER_BOTTOM), s.get_value(Settings.IMAGE_FRONT_BORDER_LEFT):s. get_value(Settings.IMAGE_FRONT_BORDER_RIGHT)] # Resize image to save some space (height = 100px) ratio = main.shape[1] / main.shape[0] resized = cv2.resize(main, (round(ratio * 100), 100)) axis = self.joystick.get_axis( s.get_value(Settings.STEERING_AXIS)) * 180 cv2.imwrite("captured/%d.png" % img_id, resized) Data().add_image("%d.png" % img_id, axis, 0, 0, 0, sequence_id) img_id += 1 time.sleep(0.150) autopilot = False manual_steering_prev = axis self.controller_thread.set_autopilot(autopilot) # Get frame of game frame_raw = ImageGrab.grab(bbox=functions.get_screen_bbox()) frame = np.uint8(frame_raw) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Relevant image region for steering angle prediction main = frame[s.get_value(Settings.IMAGE_FRONT_BORDER_TOP):s. get_value(Settings.IMAGE_FRONT_BORDER_BOTTOM), s.get_value(Settings.IMAGE_FRONT_BORDER_LEFT):s. get_value(Settings.IMAGE_FRONT_BORDER_RIGHT)] # Resize the image to the size of the neural network input layer image = scipy.misc.imresize(main, [66, 200]) / 255.0 # Let the neural network predict the new steering angle y_eval = model.y.eval(session=self.sess, feed_dict={ model.x: [image], model.keep_prob: 1.0 })[0][0] degrees = y_eval * 180 / scipy.pi steering = int(round((degrees + 180) / 180 * 32768 / 2)) # Value for vjoy controller # Set the value of the vjoy joystick to the predicted steering angle if autopilot: self.controller_thread.set_angle(steering) self.statusbar.showMessage("Autopilot active") else: self.statusbar.showMessage("Autopilot inactive") # TODO: Show steering wheel in GUI M = cv2.getRotationMatrix2D((cols / 2, rows / 2), -degrees, 1) dst = cv2.warpAffine(img_wheel, M, (cols, rows)) # functions.set_image(dst.copy(), self.steering_wheel) functions.set_image(main.copy(), self.image_front) self.controller_thread.set_autopilot(False)
import sys import os from PyQt5.QtWidgets import QApplication, QMainWindow print("Loading...") from UI.main import MainUI from database import Settings dbs = Settings() # MIGRATE if not dbs.get_value("migrated"): print("Migrating data. This may take a while...") dbs.set_value(dbs.COUNTRY_DEFAULT, "DE") dbs.set_value(dbs.COUNTRIES_MODEL, "DE") if os.path.exists("captured/data.txt") and os.path.exists( "captured/sequence.txt"): import migrate migrate.migrate() if os.path.exists("settings.py"): import settings as s dbs.set_value(dbs.CONTROLLER, s.JOYSTICK) dbs.set_value(dbs.VJOY_DEVICE, s.VJOY_DEVICE) dbs.set_value(dbs.AUTOPILOT_SOUND_ACTIVATE, s.AUTOPILOT_SOUND_ACTIVATE) dbs.set_value(dbs.ADAPTIVE_STEERING, s.ADAPTIVE_STEERING) dbs.set_value(dbs.AUTOPILOT, s.AUTOPILOT_BUTTON) dbs.set_value(dbs.STEERING_AXIS, s.STEERING_AXIS) dbs.set_value(dbs.THROTTLE_AXIS, s.THROTTLE_AXIS) dbs.set_value(dbs.LEFT_INDICATOR, s.INDICATOR_LEFT_BUTTON)