def broadcastTopic(topicTitle): try: logger.debug(u'Start broadcast topic:%s' % topicTitle) topic = djangodb.Topic.objects.get(title=topicTitle) if topic.alive(): topic_news = topic.news_set.all()[0] else: logger.warn(u'topic:%s is already dead, add unsubscribe task!' % topicTitle) djangodb.add_task(topic=topic, type=u'unsubscribe') return False except: logger.exception(u'topic or news may not exist in database') return False alreadyFetchedWeibos = topic.relevant_weibo.all() fetchedWeibos = weibo.getRelevantWeibo(topicTitle=topicTitle, count=50)['statuses'] logger.info(u'feteched %d weibo about topic:%s' % (len(fetchedWeibos), topicTitle)) for awb in fetchedWeibos: aweibo = djangodb.get_or_create_weibo(awb) if aweibo.comments_count < 200 and aweibo in alreadyFetchedWeibos: # 这条微薄已经推广过了,由于时间关系,后续的微薄理论上也应该推广过了 continue break else: topic.relevant_weibo.add(aweibo) auser = djangodb.get_or_create_account_from_weibo(awb['user']) if aweibo.comments_count < 200 and auser in topic.watcher.all(): # 该用户已经使用服务,不需要推广 continue if aweibo.comments_count < 200 and len(auser.remind_history.strip()) > 0: # 已经推广过至少一次或正在使用服务 continue topic.relevant_user.add(auser) # 评论推广 _shorturl = weibo.getShortUrl(Conf.get_timeline_url(topic.id)) reqInterval(10) msg = u'#%s# %s 『%s』 ^ ^' % (topicTitle, topic_news.title, _shorturl) try: weibo.postComment(weibo_id=aweibo.weibo_id, content=msg) except APIError, err: logger.warn(u'comment failed:\t%s' % (err.error)) if err.error == u'target weibo does not exist!': topic.relevant_user.remove(auser) topic.relevant_weibo.remove(aweibo) aweibo.delete() logger.info(u'remove relevant user:%s and delete weibo:%s' % (auser, aweibo)) except:
async def main(): # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--conf", required=True, help="Path to the input configuration file") args = vars(ap.parse_args()) # load the configuration file and label encoder conf = Conf(args["conf"]) await asyncio.gather(read_frame(), process_frame(conf)) cv2.destroyAllWindows()
def remindUserTopicUpdates(topicTitle): try: logger.debug(u'Start remind user for topic:%s' % topicTitle) topic = djangodb.Topic.objects.get(title=topicTitle) if topic.alive(): topic_news = topic.news_set.all()[0] else: logger.warn(u'topic:%s is already dead, add unsubscribe task!' % topicTitle) djangodb.add_task(topic=topic, type=u'unsubscribe') return False except: logger.exception(u'topic or news may not exist in database') return False topicWatchers = topic.watcher.all() topicWatcherWeibo = topic.watcher_weibo.all() ''' 得到订阅该话题的所有用户,分两类,已经授权的和没有授权的 ''' watcherWithAuth = set() watcherWithoutAuth = set() for watcher in topicWatchers: if watcher.has_oauth(): watcherWithAuth.add(watcher) else: watcherWithoutAuth.add(watcher) ''' 筛选出其中需要提醒的用户,分为四类: watcherWithoutStatusAndAuth watcherWithStatusAndAuth watcherWithStatusWithoutAuth watcherWithoutStatusWithAuth ''' watcherWithStatusAndAuth = set() watcherWithStatusWithoutAuth = set() for watcherWeibo in topicWatcherWeibo: watcher = watcherWeibo.user if not watcher.to_remind(): # 去掉不需要提醒的用户 continue watcher.original_weibo = watcherWeibo # 人工添加的字段 if watcher in watcherWithAuth: watcherWithStatusAndAuth.add(watcher) elif watcher in watcherWithoutAuth: watcherWithStatusWithoutAuth.add(watcher) # 去掉不需要提醒的用户 watcherWithoutStatusAndAuth = set([watcher for watcher in (watcherWithoutAuth - watcherWithStatusWithoutAuth) if watcher.to_remind()]) watcherWithoutStatusWithAuth = set([watcher for watcher in (watcherWithAuth - watcherWithStatusAndAuth) if watcher.to_remind()]) _shorturl = weibo.getShortUrl(Conf.get_timeline_url(topic.id)) _msg = u'#%s#有新进展:%s 『%s』' % (topicTitle, topic_news.title, _shorturl) reqInterval(61) logger.debug(u'topicWatcherWeibo:%s' % topicWatcherWeibo) logger.debug(u'topicWatchers:%s' % topicWatchers) logger.debug(u'watcherWithAuth:%s' % watcherWithAuth) logger.debug(u'watcherWithoutAuth:%s' % watcherWithoutAuth) logger.debug(u'posgMsg:%s' % _msg) _user_reminded = [] ''' 先更新有授权同时也发过微博的用户的状态 ''' for watcher in watcherWithStatusAndAuth: ''' 自己转发或评论自己的原始微博提醒自己,如果允许提醒他人的话,顺带提醒~ ''' [access_token, expires_in] = djangodb.get_weibo_auth_info(watcher.weiboId) _weibo = weiboAPI.weiboAPI(access_token=access_token, \ expires_in=expires_in, \ u_id=watcher.weiboId) watcher_btw = None if watcher.allow_remind_others and watcherWithStatusWithoutAuth: watcher_btw = watcherWithStatusWithoutAuth.pop() postMsg = _msg + u' @' + watcher_btw.weiboName + u' 顺便提醒你一下~' else: postMsg = _msg + u' @' + watcher.weiboName logger.info(u'remind user:%s \ntopic:%s \nupdate with msg:%s\noriginalWeibo:%s' % \ (watcher.weiboName, topicTitle, postMsg, watcher.original_weibo)) res = {} try: if watcher.repost_remind: res[u'type'] = u'repost status' res[u'status'] = _weibo.repostStatus(weibo_id=watcher.original_weibo.weibo_id, content=postMsg) else: res[u'type'] = u'comment status' res[u'status'] = _weibo.postComment(weibo_id=watcher.original_weibo.weibo_id, content=postMsg) except APIError, err: logger.warn(u'%s failed:\t%s' % (res[u'type'], err.error)) if err.error == u'target weibo does not exist!': topic.watcher_weibo.remove(watcher.original_weibo) topic.watcher.remove(watcher) logger.info(u'remove watcher:%s and delete watcherWeibo:%s' % (watcher, watcher.original_weibo)) watcher.original_weibo.delete() else: logger.exception(u'') else: logger.info(u'%s Succeed!' % res[u'type']) if watcher_btw: watcher_btw.add_remind() watcher.add_remind() logger.info(u'added remind history for user: [%s, %s]' % (watcher.weiboName, watcher_btw)) finally:
import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--conf", required=True, help="path to the configuration file") ap.add_argument("-i", "--image", required=True, help="path to the image to be classified") args = vars(ap.parse_args()) # load the configuration file conf = Conf(args["conf"]) # load the classifier, then initialize the Histogram of Oriented Gradients descriptor # and the object detector model = pickle.loads(open(conf["classifier_path"], "rb").read()) hog = HOG(orientations=conf["orientations"], pixelsPerCell=tuple(conf["pixels_per_cell"]), cellsPerBlock=tuple(conf["cells_per_block"]), normalize=conf["normalize"], block_norm="L1") od = ObjectDetector(model, hog) # load the image and convert it to grayscale image = cv2.imread(args["image"]) image = imutils.resize(image, width=min(260, image.shape[1])) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
djangodb.add_task(topic=mtopic, type=u"subscribe") else: logger.debug(u"step4: topic:%s already in track" % mtopictitle) is_new_topic = False mtopic.watcher.add(muser) mtopic.watcher_weibo.add(mweibo) mtopic.save() # step 5: 提醒用户订阅成功 try: if is_new_topic: shorturl = weibo.getShortUrl(Conf.site_url) remind_msg = u"订阅成功,我们正在整理资料,之后会将该事件的来龙去脉和最新消息推送给您! 详见:『%s』" % shorturl else: shorturl = weibo.getShortUrl(Conf.get_timeline_url(topicId=mtopic.id)) remind_msg = u"订阅成功,您可以到『%s』获取该事件的来龙去脉,同时我们会将发展动态即时推送给您~" % shorturl except APIError, err: logger.exception(u"Get short url exception:%s" % err.error) remind_msg = u"订阅成功~" finally: reqInterval(31) try: sucPostCmt = weibo.postComment(mweibo.weibo_id, remind_msg) except APIError, err: sucPostCmt = False logger.info(u"fail to post comment for weibo:%s" % mweibo) if err.error == "target weibo does not exist!": mtopic.watcher_weibo.remove(mweibo) mtopic.watcher.remove(muser)
from utils import Conf from imutils import paths import face_recognition import argparse import pickle import cv2 import os config_file = "/home/pi/Desktop/Attendance Management System/config/config.json" conf = Conf(config_file) print("[INFO] quantifying faces...") imagePaths = list( paths.list_images(os.path.join(conf["dataset_path"], conf["class"]))) knownEncodings = [] knownNames = [] for (i, imagePath) in enumerate(imagePaths): print("[INFO] processing image {}/{}".format(i + 1, len(imagePaths))) print(imagePath) name = imagePath.split(os.path.sep)[-2] print(name) image = cv2.imread(imagePath) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) encodings = face_recognition.face_encodings(rgb) for encoding in encodings: knownEncodings.append(encoding) knownNames.append(name) print("[INFO] serializing encodings...") data = {"encodings": knownEncodings, "names": knownNames} f = open(conf["encodings_path"], "wb") f.write(pickle.dumps(data))
time.sleep(5) # Processes results if status >= 400: light.info( "[ERROR] Could not send data after 5 attempts, please check \ your token credentials and internet connection") return False # light.info("[INFO] request made properly, your device is updated") return True def send_action(self, trackingId, actionName): light.info("send trackingId {} {} ".format(trackingId, actionName)) thread = threading.Thread(target=self._send_action, args=( trackingId, actionName, )) thread.daemon = True thread.start() if __name__ == '__main__': config_server = '../jetson/configs.json' conf = Conf(config_server) light_api = ApiLight(conf) light_api.send_action(123, "out")
help="Path to input video") ap.add_argument("-c","--config", default="./config.json", help="Path to the input configuration file") ap.add_argument("-s","--save",default=False, help="Save processed video (True/False)") args = vars(ap.parse_args()) # initialize the lit of class labels MobileNet SSD CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] # load the configuration file conf = Conf(args["config"]) # load our serialized model from disk def load_model(): print("[INFO] Loading model...") if os.path.isfile(conf["prototxt_path"]) and os.path.isfile(conf["model_path"]): # net = cv2.dnn.readNetFromCaffe("./MobileNetSSD/MobileNetSSD_deploy.prototxt", # "./MobileNetSSD/MobileNetSSD_deploy.caffemodel") net = cv2.dnn.readNetFromCaffe(conf["prototxt_path"],conf["model_path"]) print("[INFO] Loaded model successfully...") return net else: print("Model is not found...") # main function
def run_core(conf): # bait global lock, frame_out detector_lock = threading.Lock() logruncv.info('Get camera List to run') # cam_cfgs = get_config_file() # camera_infor = Conf(conf['camera_info']) camera_infor = Conf(conf['camera_info']) zone_infor = Conf(conf['zone_info']) if camera_infor['camera_link'] is None or camera_infor[ 'camera_link'] is None or camera_infor['camera_id'] is None: raise "camera_infor slack information" if zone_infor['1'] is None or zone_infor['2'] is None or zone_infor[ '3'] is None: raise "zone_infor slack information" cam_cfgs = {} cam_cfgs['cam_Link'] = camera_infor['camera_link'] cam_cfgs['step'] = 1 cam_cfgs['cam_Name'] = camera_infor['camera_name'] cam_cfgs['cam_ID'] = camera_infor['camera_id'] cam_cfgs['funcs'] = [] zone_fillter = {} counter_infor = {} zone_fillter["func_ID"] = 5 zone_fillter["func_Name"] = "zone filtter" zone_fillter["func_note"] = decode_note_polygon(zone_infor['1']) counter_infor["func_ID"] = 1 counter_infor["func_Name"] = "counter" counter_infor["func_line"] = decode_note_counter(zone_infor['2']) counter_infor["func_pont"] = decode_note_counter(zone_infor['3']) cam_cfgs['funcs'].append(zone_fillter) cam_cfgs['funcs'].append(counter_infor) logruncv.info(cam_cfgs) # start 1 thread for 1 camera thread = threading.Thread(target=core_thread, args=(conf, cam_cfgs, detector_lock, frame_out)) thread.daemon = True thread.start() # start the flask app app.run(host='0.0.0.0', port=8888, debug=False, threaded=True, use_reloader=False)
def preloop(self): cfg = Conf('../config.ini', 'LOCAL') self.game = GoldQuest(cfg)