def __init__(self): self.config = Config() self.httpConfig = { 'getUrl': 'http://api.live.bilibili.com/ajax/msg', 'sendUrl': 'http://api.live.bilibili.com/msg/send', 'header': { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "utf-8", "Accept-Language": "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3", "Connection": "keep-alive", "Cookie": self.config.get('cookie'), "Host": "api.live.bilibili.com", "Referer": "http://live.bilibili.com/" + self.config.get('roomId'), "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0" } } self.sendLock = False
def create_report(tinker_list, email): plots = [] skipped = [] outfile = Config.report_dir() / '{}.stock_daily_report.pdf'.format(email) with PdfPages(outfile) as pdf: for tinker in tinker_list: # print(tinker) stock = (convert_tinker(tinker)) # print(stock) try: df = process_df(stock, Config.startdate(), Signal.MACD_long()) # print(df) plots.append(MACD_plot(df, stock)) pdf.savefig() # saves the current figure into a pdf page plt.close() except Exception as e: # print(e) print('skipped:', email, tinker) skipped.append(tinker) print(f'Plots: {len(plots)}, skipped: {len(skipped)}') d = pdf.infodict() d['Title'] = 'Stock report' d['Author'] = 'Pri ' # d['Subject'] = 'How to create a multipage pdf file and set its metadata' # d['Keywords'] = 'PdfPages multipage keywords author title subject' d['CreationDate'] = datetime.datetime.today() d['ModDate'] = datetime.datetime.today() return outfile
def __init__(self, path=None, config=None, apply_defaults=True, verify=True): if config is None: if path is None: self.config = Config(apply_defaults) else: self.config = self.load_config(path) if verify: self.config.verify()
def getDriver(self,phoneName): global desireCap global androidDriver configReader = Config() desireCap = configReader.getDesiredCap(phoneName) androidDriver = webdriver.Remote(desireCap['url'],desireCap) return androidDriver
def __init__(self): self.danmu = Danmu() self.config = Config() self.neteaseMusic = NeteaseMusic() self.log = Log('Danmu Service') self.commandMap = { '点歌=': 'selectSongAction', 'id=': 'selectSongByIdAction', 'mv=': 'selectMvByIdAction', '切歌': 'DebugAction' } pass
def __init__(self, board, parent=None): QWidget.__init__(self, parent) self.parent = parent self.b = board self.config = Config("config/config.conf") # centrer la fenetre qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) # zone pour changer le dossier contenant les musiques labPath = QLabel("Chemin des musiques :") self.entryPath = QLineEdit() path = self.config.getValueOf("path") if path: self.entryPath.setText(path) bBrowsePath = QPushButton("Parcourir...") bBrowsePath.clicked.connect(self.selectPath) # zone en bas a droite pour valider ou non les changements bAccept = QPushButton("Valider") bAccept.setProperty("class", "specialButton") bAccept.clicked.connect(self.acceptModifications) bCancel = QPushButton("Annuler") bCancel.setProperty("class", "specialButton") bCancel.clicked.connect(self.cancelModifications) # disposition de la fenetre layout = QVBoxLayout() self.setLayout(layout) layoutPath = QHBoxLayout() layoutPath.addWidget(self.entryPath) layoutPath.addWidget(bBrowsePath) layoutLabEntry = QVBoxLayout() layoutLabEntry.addWidget(labPath) layoutLabEntry.addLayout(layoutPath) layoutBottom = QHBoxLayout() layoutBottom.addStretch() layoutBottom.addWidget(bAccept) layoutBottom.addWidget(bCancel) layout.addLayout(layoutLabEntry) layout.addStretch() layout.addLayout(layoutBottom)
def send_report(): print('Send report') data = Config.load_data() for email_add in data: print(email_add, Config.sender_id) if not data[email_add]['stop']: msg = Mail.create_message_with_attachment( Config.sender_id(), email_add, Config.subject(), # Config.body(), stock_news(data[email_add]['watch']), get_report(email_add), body_type='html') Mail.send_message(Config.Service(), Config.sender_id(), msg)
def __init__(self,nodeName,filePath=None): # 生成配置文件对象 # ./config.yaml configPath=f'.{os.sep}config.yaml' config = Config(configPath) # 存放excel对象 self.excelOjb = None # 创建excel对象 # 根据配置文件中的文件名进行创建 if 'order'==nodeName: # ./Resources/国内订单-7月n.xlsx filePath=f'.{os.sep}Resources{os.sep}{config.data[nodeName]["fileName"]}' # 创建EXCEL对象 self.__readExcel(filePath, config.data[nodeName]['sheet']['sheetName']) # 根据参数传进来的filePath值进行创建 else: # 文件路径直接读 self.__readExcel(filePath, config.data[nodeName]['sheet']['sheetName']) # 如果是快递单目录,设置合同规则 if 'expressDelivery'==nodeName: self.excelOjb.contractNoRegex=config.data[nodeName]['contractNoRegex'] # 设置excel对象的列信息 self.excelOjb.columnMap = config.data[nodeName]['sheet']['column']['columnName'] # 设置excel对象的 字段所在行号 self.excelOjb.columnNameRow = config.data[nodeName]['sheet']['column']['columnNameRow'] # 设置excel对象的 从第几行开始读取数据 self.excelOjb.dateSatrtRow = config.data[nodeName]['sheet']['dateSatrtRow'] # 获取EXCEL指定列所在单元格位置 self.__getFieldCol(self.excelOjb)
def main(): args = Parser().initilaize_arg_parser() config = Config().collect_config() try: if (args.email == 'gmail'): connection = Gmail() connection.connect() connection.login() connection.select_folder('INBOX') if (args.uid is None): connection.collect_emails() else: connection.collect_emails(args.uid) connection.disconnect() elif (args.email == 'outlook'): connection = Outlook() connection.connect() connection.login() connection.select_folder('Sent Directly To Me') if (args.uid is None): connection.collect_emails() else: connection.collect_emails_by_uid(args.uid) connection.disconnect() except KeyboardInterrupt as err: print('') print('Exiting monty mail.') except Exception as err: print(err)
def __init__(self): # 初始化变量 self.config = Config() self.cookies = self.config.getCookies() self.log = Log('service/Msg') self.msg = Msg(self.cookies) self.robot = Robot(self.config.get('api_keys')) self.uid = int(self.cookies['DedeUserID']) self.admin_ids = self.config.get('admin_ids') self.receiver_ids = self.config.get('receiver_ids') self.cookies_str = self.config.get('cookies') self.userList = {} self.groupList = {} self.is_private = self.config.get('is_private')
def __init__(self): if not self.conf: Config.__init__(self) here_logs = "./logs" # filename = re.sub(r"py$", "log", basename(self.script), 1) self._file = here_logs + "/bots.log" self._bad_file = here_logs + "/bots.err" formatter = logging.Formatter(self._format) fileHandler = logging.FileHandler(self._bad_file) streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) self._bad_logger = logging.getLogger(self._file) self._bad_logger.setLevel(logging.ERROR) self._bad_logger.addHandler(fileHandler) self._bad_logger.addHandler(streamHandler)
def getDriver(self,phoneName): self.desireCap = Config.getDesiredCap(phoneName) try: self.driver = webdriver.Remote(self.desireCap['url'],self.desireCap) except Exception as err: print("Initializing Driver error") return self.driver
def __init__(self): self.config = Config() self.http_config = { 'getUrl': 'http://api.live.bilibili.com/ajax/msg', 'sendUrl': 'http://api.live.bilibili.com/msg/send', 'header': { "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6", "Connection": "keep-alive", "Cookie": self.config.get('cookie', 'danmu'), "Host": "api.live.bilibili.com", "Referer": "http://live.bilibili.com/" + self.config.get('roomId'), "User-Agent": self.config.get('User-Agent', 'headers') } } self.send_lock = False
def __init__(self, tabledesc, dbfile=None): self.tablename = tabledesc[0] self.tablefield = tabledesc[1] if dbfile: self.dbfile = dbfile else: conf = Config() self.dbfile = str(conf.properties.get("ProjectRoot")) + str( conf.properties.get("DBFile")) self.conn = sqlite3.connect(self.dbfile) self.conn.isolation_level = None
def main(): args = Parser().initilaize_arg_parser() config = Config().collect_config() if (args.function == 'iqr'): IQR().calc_iqr() elif (args.function == 'sd'): SD().calc_sd() else: print( "Please provide a valid function. -h to see list of available options." )
class ConfigWindow(QWidget): ''' fenetre de configuration du lecteur :param board: le tableau de bord du lecteur :type board: model.Board ''' def __init__(self, board, parent=None): QWidget.__init__(self, parent) self.parent = parent self.b = board self.config = Config("config/config.conf") # centrer la fenetre qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) # zone pour changer le dossier contenant les musiques labPath = QLabel("Chemin des musiques :") self.entryPath = QLineEdit() path = self.config.getValueOf("path") if path: self.entryPath.setText(path) bBrowsePath = QPushButton("Parcourir...") bBrowsePath.clicked.connect(self.selectPath) # zone en bas a droite pour valider ou non les changements bAccept = QPushButton("Valider") bAccept.setProperty("class", "specialButton") bAccept.clicked.connect(self.acceptModifications) bCancel = QPushButton("Annuler") bCancel.setProperty("class", "specialButton") bCancel.clicked.connect(self.cancelModifications) # disposition de la fenetre layout = QVBoxLayout() self.setLayout(layout) layoutPath = QHBoxLayout() layoutPath.addWidget(self.entryPath) layoutPath.addWidget(bBrowsePath) layoutLabEntry = QVBoxLayout() layoutLabEntry.addWidget(labPath) layoutLabEntry.addLayout(layoutPath) layoutBottom = QHBoxLayout() layoutBottom.addStretch() layoutBottom.addWidget(bAccept) layoutBottom.addWidget(bCancel) layout.addLayout(layoutLabEntry) layout.addStretch() layout.addLayout(layoutBottom) def selectPath(self): ''' demande a l'utilisateur de choisir un dossier et rentre le chemin dans l'input ''' folder = QFileDialog.getExistingDirectory( self, 'Select directory', expanduser("~")) if folder: self.entryPath.setText(folder) def acceptModifications(self): ''' met en place les parametres et ferme la fenetre ''' folder = self.entryPath.text() self.config.setValueOf("path", folder) self.config.save() self.b.setDirectory(folder) self.close() def cancelModifications(self): self.close() def close(self): QWidget.close(self) self.parent.close()
import numpy as np import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset from util.Config import Config from util.Data import csv_to_tensor, ImgDataset from model import CH_net model = CH_net().cuda() model.load_state_dict(torch.load('res_net.pth')) config = Config(model) config.optimizer = torch.optim.Adam(config.model.parameters(), lr=0.001) config.lr_optim = torch.optim.lr_scheduler.CosineAnnealingLR(config.optimizer, T_max=32) test_transform = transforms.Compose([ transforms.ToPILImage(), transforms.ToTensor(), ]) test_x = csv_to_tensor('data/test.csv', mode='test') test_set = ImgDataset(test_x, transform=test_transform) test_loader = DataLoader(test_set, batch_size=config.batch_size, shuffle=False) #testing model.eval() prediction = [] with torch.no_grad(): for i, data in enumerate(test_loader): test_pred = config.model(data.cuda()) test_label = np.argmax(test_pred.cpu().data.numpy(), axis=1)
class Danmu(object): def __init__(self): self.config = Config() self.http_config = { 'getUrl': 'http://api.live.bilibili.com/ajax/msg', 'sendUrl': 'http://api.live.bilibili.com/msg/send', 'header': { "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6", "Connection": "keep-alive", "Cookie": self.config.get('cookie', 'danmu'), "Host": "api.live.bilibili.com", "Referer": "http://live.bilibili.com/" + self.config.get('roomId'), "User-Agent": self.config.get('User-Agent', 'headers') } } self.send_lock = False def get(self): """获取弹幕(单次上限10条)""" room_id = self.config.get('roomId') post_data = {'token:': '', 'csrf_token:': '', 'roomid': room_id} response = requests.post(url=self.http_config['getUrl'], data=post_data, headers=self.http_config['header']).json() # 获取最后的弹幕时间 config_time = self.config.get(module='danmu', key='timestamp') config_time = float(config_time) if config_time else 0 if 'code' in response and response['code'] == 0: # 解析弹幕 result = [] for danmu in response['data']['room']: # 判断弹幕是否被处理过 current_time = time.mktime( time.strptime(danmu['timeline'], "%Y-%m-%d %H:%M:%S")) if config_time >= current_time: continue self.config.set(module='danmu', key='timestamp', value=current_time) result.append({ 'name': danmu['nickname'], 'time': danmu['timeline'], 'uid': str(danmu['uid']), 'text': danmu['text'] }) return result else: raise Exception('Cookie 无效') def send(self, text): """发送弹幕""" elapsed_time = 0 while self.send_lock: time.sleep(1) # 判断等待超时 elapsed_time += 1 if (elapsed_time > 30): return None # 将超过20字的弹幕切片后发送 length_limit = 20 if len(text) > length_limit: for i in range(0, len(text), length_limit): self.send(text[i:i + length_limit]) time.sleep(1.5) return True # 准备数据 self.send_lock = True try: room_id = self.config.get('roomId') post_data = { 'color': '16777215', 'csrf_token': self.config.get("csrf_token", 'danmu'), 'fontsize': '25', 'mode': '1', 'msg': text, 'rnd': '1543573073', 'roomid': room_id } # 发送请求 response = requests.post( url=self.http_config['sendUrl'], data=post_data, headers=self.http_config['header']).json() return 'code' in response and response['code'] == 0 except Exception as e: raise e finally: self.send_lock = False
import random import time from models.FairIR import FairIR from util.Config import Config from util.IO import mkdir_p, copy_source_to_dir if __name__ == "__main__": parser = argparse.ArgumentParser( description='Solve paper matching with FairIR.') parser.add_argument('config', type=str, help='config file.') args = parser.parse_args() # Load data & initialize config = Config(args.config) loads = np.load(config.load_f) covs = np.load(config.cov_f) scores = np.load(config.score_f) if config.load_lb_f: loads_lb = np.load(config.load_lb_f) else: loads_lb = None rand = random.Random(config.random_seed) config.random = rand print('#info random seed %s' % config.random_seed) debug = config.debug fairness_threshold = config.fairness_threshold assert(config.match_model == 'fairir' or config.match_model == 'fairir-lb')
class DanmuService(Service): def __init__(self): self.danmu = Danmu() self.config = Config() self.neteaseMusic = NeteaseMusic() self.log = Log('Danmu Service') self.commandMap = { '点歌=': 'selectSongAction', 'id=': 'selectSongByIdAction', 'mv=': 'selectMvByIdAction', '切歌': 'DebugAction' } pass def run(self): try: self.parseDanmu() time.sleep(1.5) except Exception as e: self.log.error(e) # 解析弹幕 def parseDanmu(self): danmuList = self.danmu.get() if danmuList: for danmu in danmuList: self.log.debug('%s: %s' % (danmu['name'], danmu['text'])) if danmu['name'] != self.config.get('miaoUser'): # 不响应弹幕姬的弹幕 danmu['text'] = danmu['text'].replace(' ', '') # 删除空格防和谐 self.danmuStateMachine(danmu) pass # 将对应的指令映射到对应的Action上 def danmuStateMachine(self, danmu): text = danmu['text'] commandAction = '' for key in self.commandMap: # 遍历查询comand是否存在 若存在则反射到对应的Action if text.find(key) == 0 and hasattr(self, self.commandMap[key]): danmu['command'] = danmu['text'][len(key):len(danmu['text'])] getattr(self, self.commandMap[key])(danmu) break pass # 歌曲名点歌 def selectSongAction(self, danmu): self.log.info('%s 点歌 [%s]' % (danmu['name'], danmu['command'])) command = danmu['command'] song = [] # 按歌曲名-歌手点歌 if command.find('-') != -1: detail = command.split('-') if len(detail) == 2: song = self.neteaseMusic.searchSingle(detail[0], detail[1]) else: # 查询失败 song = {} # 直接按歌曲名点歌 else: song = self.neteaseMusic.searchSingle(danmu['command']) if song: self.danmu.send('%s点歌成功' % song['name']) DownloadQueue.put({ 'type': 'id', 'info': song, 'username': danmu['name'], 'time': danmu['time'] }) else: # 未找到歌曲 self.danmu.send('找不到%s' % danmu['command']) self.log.info('找不到%s' % danmu['command']) # 通过Id点歌 def selectSongByIdAction(self, danmu): self.log.info('%s ID [%s]' % (danmu['name'], danmu['command'])) command = danmu['command'] try: song = self.neteaseMusic.getInfo(command) if song: self.danmu.send('%s点歌成功' % song['name']) DownloadQueue.put({ 'type': 'id', 'info': song, 'username': danmu['name'], 'time': danmu['time'] }) else: # 未找到歌曲 raise Exception('未找到歌曲') except Exception as e: self.danmu.send('找不到%s' % danmu['command']) self.log.info('找不到%s' % danmu['command']) # 通过Id点Mv def selectMvByIdAction(self, danmu): self.log.info('%s MV [%s]' % (danmu['name'], danmu['command'])) command = danmu['command'] try: mv = self.neteaseMusic.getMv(command) if mv: self.danmu.send('%s点播成功' % mv['name']) DownloadQueue.put({ 'type': 'mv', 'info': mv, 'username': danmu['name'], 'time': danmu['time'] }) else: # 未找到歌曲 raise Exception('未找到MV') except Exception as e: self.danmu.send('找不到%s' % danmu['command']) self.log.info('找不到%s' % danmu['command']) def DebugAction(self, danmu): if danmu['name'] in self.config.get('adminUser'): if danmu['text'] == '切歌': os.system( "kill `ps a|grep 'ffmpeg -re'|grep -v 'sh'|grep -v 'grep'|awk '{print $1}'`" ) self.danmu.send('切歌成功')
def __init__(self): self.danmu = Danmu() self.log = Log('Media Service') self.config = Config()
def load_config(path): configuration = Config(False) configFile = configparser.ConfigParser() try: configFile.read(path) with open(path) as f: configFile.read_file(f) except IOError as error: print("File at \"", path, "\" not found.", sep="") raise error try: # Main ratio = float(configFile.get("Main", "LeftToRightRatio")) if not 0 <= ratio <= 2: raise configparser.ParsingError("LeftToRightRatio out of bounds ({:.3f} OOR [0,2])".format(ratio)) if ratio <= 1: configuration.MotorLeftRatio = ratio configuration.MotorRightRatio = 1 else: configuration.MotorLeftRatio = 1 configuration.MotorRightRatio = 1 / ratio configuration.PiCamEnabled = configFile.get("Main", "CamEnabled").lower() == "true" configuration.I2CBus = int(configFile.get("Main", "i2cBus")) if not 0 <= configuration.I2CBus <= 2: raise configparser.ParsingError("Bus out of bounds ({:d} OOR [0,2])".format(configuration.I2CBus)) configuration.MotorDriverFrequency = int(configFile.get("Main", "MotorDriverFrequency")) if not 1 <= configuration.MotorDriverFrequency <= 10000: raise configparser.ParsingError( "Frequency out of bounds ({:d} OOR [1,10000])".format(configuration.MotorDriverFrequency)) configuration.Handshake = configFile.get("Main", "Handshake").lower() == "true" # Sensors configuration.UltraSonicState = int(configFile.get("Sensors", "USMode")) configuration.UltraSonicInterruptPinEnabled = configFile.get("Sensors", "USInterruptPin").lower() == "true" configuration.UltraSonicMode = int(configFile.get("Sensors", "USPollingMethod")) if not 0 <= configuration.UltraSonicMode <= 4: raise configparser.ParsingError("Method {:d} not recognized".format(configuration.UltraSonicMode)) configuration.UltraSonicLock = configFile.get("Sensors", "USLock").lower() == "true" if configuration.UltraSonicLock and configuration.UltraSonicMode == 0: raise configparser.ParsingError("US Lock is enabled but there is no polling method") configuration.UltraSonicThreshold = int(configFile.get("Sensors", "USDistanceInterrupt")) if configuration.UltraSonicThreshold < 0: raise configparser.ParsingError( "Distance cannot be negative ({:d} < 0)".format(configuration.UltraSonicThreshold)) if configuration.UltraSonicMode == 2 and configuration.UltraSonicThreshold > 29: raise configparser.ParsingError( "Threshold out of bounds ({:d} OOR [0,29])".format(configuration.UltraSonicThreshold)) configuration.UltraSonicPollingRate = int(configFile.get("Sensors", "USPollingRate")) if configuration.UltraSonicMode != 3 and not 1 <= configuration.UltraSonicPollingRate <= 100: raise configparser.ParsingError( "Polling rate out of bounds ({:d} OOR [1,100])".format(configuration.UltraSonicPollingRate)) configuration.UltraSonicPollingDelay = float(configFile.get("Sensors", "USDelay")) if configuration.UltraSonicMode != 3 and configuration.UltraSonicPollingDelay <= 0: raise configparser.ParsingError( "Delay must be positive number ({:.2f} <= 0)".format(configuration.UltraSonicPollingDelay)) # Pins configuration.UltraSonicInterruptPin = int(configFile.get("Pins", "InterruptPin")) configuration.MotorDriverLeftPWM = int(configFile.get("Pins", "MotorDriverLeftPWM")) configuration.MotorDriverRightPWM = int(configFile.get("Pins", "MotorDriverRightPWM")) configuration.MotorDriverLeftForwards = int(configFile.get("Pins", "MotorDriverLeftForwards")) configuration.MotorDriverLeftBackwards = int(configFile.get("Pins", "MotorDriverLeftBackwards")) configuration.MotorDriverRightForwards = int(configFile.get("Pins", "MotorDriverRightForwards")) configuration.MotorDriverRightBackwards = int(configFile.get("Pins", "MotorDriverRightBackwards")) except configparser.Error as error: print("Config file {} contains errors.".format(path)) raise error return configuration
from util.Config import Config from util.Data import csv_to_tensor, ImgDataset from model import CH_net train_x, train_y = csv_to_tensor('data/train.csv', mode='train') train_transform = transforms.Compose([ transforms.ToPILImage(), #transforms.RandomAffine(10, translate=(0.1,0.1)), transforms.RandomRotation(15), transforms.ToTensor( ), # 將圖片轉成 Tensor,並把數值 normalize 到 [0,1] (data normalization) ]) model = CH_net().cuda() config = Config(model) config.optimizer = torch.optim.Adam(config.model.parameters(), lr=0.001) config.lr_optim = torch.optim.lr_scheduler.CosineAnnealingLR(config.optimizer, T_max=32) train_set = ImgDataset(train_x, train_y, transform=train_transform) train_loader = DataLoader(train_set, batch_size=config.batch_size, shuffle=True) #start training config.epoch = 30 change1 = 0 change2 = 0 for epoch in range(config.epoch): '''
class ConfigHelper(object): def __init__(self, path=None, config=None, apply_defaults=True, verify=True): if config is None: if path is None: self.config = Config(apply_defaults) else: self.config = self.load_config(path) if verify: self.config.verify() @staticmethod def load_config(path): configuration = Config(False) configFile = configparser.ConfigParser() try: configFile.read(path) with open(path) as f: configFile.read_file(f) except IOError as error: print("File at \"", path, "\" not found.", sep="") raise error try: # Main ratio = float(configFile.get("Main", "LeftToRightRatio")) if not 0 <= ratio <= 2: raise configparser.ParsingError("LeftToRightRatio out of bounds ({:.3f} OOR [0,2])".format(ratio)) if ratio <= 1: configuration.MotorLeftRatio = ratio configuration.MotorRightRatio = 1 else: configuration.MotorLeftRatio = 1 configuration.MotorRightRatio = 1 / ratio configuration.PiCamEnabled = configFile.get("Main", "CamEnabled").lower() == "true" configuration.I2CBus = int(configFile.get("Main", "i2cBus")) if not 0 <= configuration.I2CBus <= 2: raise configparser.ParsingError("Bus out of bounds ({:d} OOR [0,2])".format(configuration.I2CBus)) configuration.MotorDriverFrequency = int(configFile.get("Main", "MotorDriverFrequency")) if not 1 <= configuration.MotorDriverFrequency <= 10000: raise configparser.ParsingError( "Frequency out of bounds ({:d} OOR [1,10000])".format(configuration.MotorDriverFrequency)) configuration.Handshake = configFile.get("Main", "Handshake").lower() == "true" # Sensors configuration.UltraSonicState = int(configFile.get("Sensors", "USMode")) configuration.UltraSonicInterruptPinEnabled = configFile.get("Sensors", "USInterruptPin").lower() == "true" configuration.UltraSonicMode = int(configFile.get("Sensors", "USPollingMethod")) if not 0 <= configuration.UltraSonicMode <= 4: raise configparser.ParsingError("Method {:d} not recognized".format(configuration.UltraSonicMode)) configuration.UltraSonicLock = configFile.get("Sensors", "USLock").lower() == "true" if configuration.UltraSonicLock and configuration.UltraSonicMode == 0: raise configparser.ParsingError("US Lock is enabled but there is no polling method") configuration.UltraSonicThreshold = int(configFile.get("Sensors", "USDistanceInterrupt")) if configuration.UltraSonicThreshold < 0: raise configparser.ParsingError( "Distance cannot be negative ({:d} < 0)".format(configuration.UltraSonicThreshold)) if configuration.UltraSonicMode == 2 and configuration.UltraSonicThreshold > 29: raise configparser.ParsingError( "Threshold out of bounds ({:d} OOR [0,29])".format(configuration.UltraSonicThreshold)) configuration.UltraSonicPollingRate = int(configFile.get("Sensors", "USPollingRate")) if configuration.UltraSonicMode != 3 and not 1 <= configuration.UltraSonicPollingRate <= 100: raise configparser.ParsingError( "Polling rate out of bounds ({:d} OOR [1,100])".format(configuration.UltraSonicPollingRate)) configuration.UltraSonicPollingDelay = float(configFile.get("Sensors", "USDelay")) if configuration.UltraSonicMode != 3 and configuration.UltraSonicPollingDelay <= 0: raise configparser.ParsingError( "Delay must be positive number ({:.2f} <= 0)".format(configuration.UltraSonicPollingDelay)) # Pins configuration.UltraSonicInterruptPin = int(configFile.get("Pins", "InterruptPin")) configuration.MotorDriverLeftPWM = int(configFile.get("Pins", "MotorDriverLeftPWM")) configuration.MotorDriverRightPWM = int(configFile.get("Pins", "MotorDriverRightPWM")) configuration.MotorDriverLeftForwards = int(configFile.get("Pins", "MotorDriverLeftForwards")) configuration.MotorDriverLeftBackwards = int(configFile.get("Pins", "MotorDriverLeftBackwards")) configuration.MotorDriverRightForwards = int(configFile.get("Pins", "MotorDriverRightForwards")) configuration.MotorDriverRightBackwards = int(configFile.get("Pins", "MotorDriverRightBackwards")) except configparser.Error as error: print("Config file {} contains errors.".format(path)) raise error return configuration @staticmethod def handshake(config): import smbus import time bus = smbus.SMBus(config.I2CBus) enabled = 1 if config.UltraSonicInterruptPinEnabled else 0 read = bus.read_byte_data(0x10, 50 + enabled) if read != enabled: raise HandshakeError( "Handshake failed at setting interrupt pin, sent={:d} received={:d}".format(enabled + 50, read)) time.sleep(config.UltraSonicPollingDelay/1000) enabled = 0 if config.UltraSonicState == 2 else 1 read = bus.read_byte_data(0x10, 54 + enabled) if read != enabled: raise HandshakeError( "Handshake failed at setting sensor state, sent={:d} received={:d}".format(enabled + 54, read)) time.sleep(config.UltraSonicPollingDelay/1000) if config.UltraSonicThreshold < 29: distance = config.UltraSonicThreshold read = bus.read_byte_data(0x10, distance + 60) else: distance = int((config.UltraSonicThreshold - 30) / 5) read = bus.read_byte_data(0x10, distance + 90) distance *= 5 if read != distance: raise HandshakeError( "Handshake failed at setting threshold, sent={:d} received={:d}".format(distance, read))
class MsgService(Service): def __init__(self): # 初始化变量 self.config = Config() self.cookies = self.config.getCookies() self.log = Log('service/Msg') self.msg = Msg(self.cookies) self.robot = Robot(self.config.get('api_keys')) self.uid = int(self.cookies['DedeUserID']) self.admin_ids = self.config.get('admin_ids') self.receiver_ids = self.config.get('receiver_ids') self.cookies_str = self.config.get('cookies') self.userList = {} self.groupList = {} self.is_private = self.config.get('is_private') # self.msg.send('start') def run(self): try: self.parseMsg() time.sleep(2) except Exception as e: self.log.error(e) # 解析消息 def parseMsg(self): msgList = self.msg.get() for msg in msgList: self.log.debug(msg) # 私信 if msg['receiver_type'] == 1: if msg['msg_type'] == 1: text = json.loads(msg['content'])['content'].lstrip() self.handler(text, msg['sender_uid'], 0) pass # 应援团 elif msg['receiver_type'] == 2: if (0 in self.receiver_ids or int(msg['receiver_id'] in self.receiver_ids)) \ and msg['msg_type'] == 1 and 'at_uids' in msg and self.uid in msg['at_uids']: # 处理@ text = json.loads(msg['content'])['content'].lstrip() text = text.replace('\u0011', '') # IOS客户端的@前后有这两个控制字符 text = text.replace('\u0012', '') if text.find('@' + self.getUserName(self.uid)) == 0: text = text[len(self.getUserName(self.uid)) + 1:].lstrip() self.handler(text, msg['sender_uid'], msg['receiver_id']) pass pass # 消息处理函数 def handler(self, text, user_id, group_id): # 管理员命令 ot = '' if text.find('#') == 0 \ and (user_id == self.groupList[group_id]['admin'] or user_id in self.admin_ids): text = text[1:] if user_id in self.admin_ids: if text == '切换': old = self.robot.swiRobot() ot = '已从%d号切换到%d号(我比前一位聪明哦~)' % (old, self.robot.apiKeyNo) if text == '睡觉': self.groupList[group_id]['off'] = 1 ot = '已准备睡觉,各位晚安~' elif text == '醒醒': self.groupList[group_id]['off'] = 0 ot = '又是全新的一天,早安!' if ot == '': ot = '对方不想理你,并抛出了个未知的异常(◔◡◔)' # 聊天 else: # 私信关闭状态 if group_id == 0 and self.is_private == 0: return # 睡觉 if group_id not in self.groupList: self.getGroupDetail(group_id) if self.groupList[group_id]['off'] == 1: return if text == '': text = '?' # 转发消息给机器人 self.log.success('[in][%s][%s] %s' % (self.groupList[group_id]['name'], self.getUserName(user_id), text)) ot = self.robot.send(text, user_id, group_id) self.log.success('[out][%s][%s] %s' % (self.groupList[group_id]['name'], self.getUserName(user_id), ot)) # 回复 # 私信 if group_id == 0: self.msg.send(ot, user_id, receiver_type=1) # 群聊 else: self.msg.send('@%s %s' % (self.getUserName(user_id), ot), group_id, receiver_type=2, at_uid=user_id) # 获取用户名 uid -> 昵称 def getUserName(self, user_id): # 每300s(5min)更新一次昵称 if user_id not in self.userList or self.userList[user_id][1] - int( time.time()) > 300: url = 'http://api.live.bilibili.com/user/v2/User/getMultiple' postData = { 'uids[0]': user_id, 'attributes[0]': 'info', 'csrf_token': self.msg.cookies['bili_jct'] } response = requests.post(url, data=postData, cookies=self.cookies).json() self.log.debug('[查询用户]' + str(response)) self.userList[user_id] = [ response['data'][str(user_id)]['info']['uname'], int(time.time()) ] return self.userList[user_id][0] # 获取群信息 群主&勋章名(替代群名) def getGroupDetail(self, group_id): if group_id not in self.groupList: if group_id == 0: self.groupList[group_id] = {'admin': 0, 'name': '私信', 'off': 0} else: url = 'https://api.vc.bilibili.com/link_group/v1/group/detail?group_id=%s' % str( group_id) response = requests.get(url).json() self.log.debug('[查询群]' + str(response)) self.groupList[group_id] = { 'admin': response['data']['owner_uid'], 'name': response['data']['fans_medal_name'], 'off': 0 }
class MediaService(Service): def __init__(self): self.danmu = Danmu() self.log = Log('Media Service') self.config = Config() self.ass = AssMaker() def run(self): try: # 判断队列是否为空 if PlayQueue.empty(): time.sleep(3) # 获取随机文件,播放 musicPath = './resource/music/' musicName = self.getRandomFile(musicPath, '.mp3') # musicName = os.path.basename(musicName) musicName = os.path.splitext(musicName)[0] task = {} # 存在详情文件 if os.path.isfile('%s%s.mp3.json' % (musicPath, musicName)): f = open('%s%s.mp3.json' % (musicPath, musicName), 'rt') task = json.loads(f.read()) f.close() else: pass self.playMusic(task) else: # 获取新的下载任务 task = PlayQueue.get() if task and 'type' in task: if task['type'] == 'id': self.playMusic(task) elif task['type'] == 'mv': self.playVedio(task) pass except Exception as e: self.log.error(e) # 播放音乐 def playMusic(self, music): self.log.info('[Music] 开始播放[%s]点播的[%s]' % (music['username'], music['info']['name'])) self.danmu.send('正在播放%s' % music['info']['name']) # 生成背景字幕 self.ass.make_ass(music, './resource/bak.ass') # 处理图片 imagePath = './resource/img/' randomImage = imagePath + self.getRandomFile(imagePath) command = ffmpeg().getImage(image=randomImage, output='./resource/bak.jpg', ass='./resource/bak.ass') command = "%s 2>> ./log/ffmpeg_img.log" % command self.log.debug(command) process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True) process.wait() # 获取歌词 assPath = '' if 'lrc' in music['info']: assPath = './resource/music/%s.mp3.ass' % music['info']['id'] # 开始播放 mp3Path = './resource/music/%s.mp3' % music['info']['id'] command = ffmpeg().getMusic(music=mp3Path, output=self.getRTMPUrl(), image='./resource/bak.jpg', ass=assPath) command = "%s 2>> ./log/ffmpeg.log" % command self.log.debug(command) process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True) process.wait() self.log.info('[Music] [%s]播放结束' % music['info']['name']) # 播放视频 def playVedio(self, music): self.log.info('[Music] 开始播放[%s]点播的[%s]' % (music['username'], music['info']['name'])) self.danmu.send('正在播放%s' % music['info']['name']) # 开始播放 vedioPath = './resource/video/%s_mv.flv' % music['info']['id'] command = ffmpeg().getVedio(vedio=vedioPath, output=self.getRTMPUrl()) command = "%s 2>> ./log/ffmpeg.log" % command self.log.debug(command) process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True) process.wait() self.log.info('[Music] [%s]播放结束' % music['info']['name']) # 获取推流地址 def getRTMPUrl(self): url = self.config.get(module='rtmp', key='url') code = self.config.get(module='rtmp', key='code') return url + code # 获取随机文件 def getRandomFile(self, path, type=None): fileList = [] if type: for filename in os.listdir(path): if os.path.splitext(filename)[1] == type: fileList.append(filename) else: fileList = os.listdir(path) if len(fileList) == 0: raise Exception('无法获取随机文件,%s为空' % path) index = random.randint(0, len(fileList) - 1) return fileList[index]
class MediaService(Service): def __init__(self): self.danmu = Danmu() self.log = Log('Media Service') self.config = Config() def run(self): try: # 判断队列是否为空 if PlayQueue.empty(): # 获取随机文件,播放 musicPath = './resource/music/' randomMusic = self.getRandomFile(musicPath) musicName = os.path.basename(randomMusic) musicName = musicName.replace(os.path.splitext(randomMusic)[1], '') self.playMusic({ 'username': '******', 'name': musicName, 'filename': musicPath + randomMusic }, True) return # 获取新的下载任务 task = PlayQueue.get() if task and 'type' in task: if task['type'] == 'music': self.playMusic(task) elif task['type'] == 'vedio': pass except Exception as e: self.log.error(e) # 播放音乐 def playMusic(self, music, autoPlay=False): imagePath = './resource/img/' randomImage = imagePath + self.getRandomFile(imagePath) self.log.info('[Music] 开始播放[%s]点播的[%s]' % (music['username'], music['name'])) self.danmu.send('正在播放 %s' % music['name']) # 获取歌词 assPath = './resource/lrc/default.ass' if 'lrc' in music: assPath = music['lrc'] # 开始播放 command = ffmpeg().getMusic(music=music['filename'], output=self.getRTMPUrl(), image=randomImage, ass=assPath) command = "%s 2>> ./log/ffmpeg.log" % command self.log.debug(command) process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True) process.wait() # 播放完毕 if not autoPlay: os.remove(path=music['filename']) self.log.info('[Music] [%s]播放结束' % music['name']) # 获取推流地址 def getRTMPUrl(self): url = self.config.get(module='rtmp', key='url') code = self.config.get(module='rtmp', key='code') return url + code # 获取随机文件 def getRandomFile(self, path): fileList = os.listdir(path) if len(fileList) == 0: raise Exception('无法获取随机文件,%s为空' % path) index = random.randint(0, len(fileList) - 1) return fileList[index]
class Danmu(object): def __init__(self): self.config = Config() self.httpConfig = { 'getUrl': 'http://api.live.bilibili.com/ajax/msg', 'sendUrl': 'http://api.live.bilibili.com/msg/send', 'header': { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "utf-8", "Accept-Language": "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3", "Connection": "keep-alive", "Cookie": self.config.get('cookie'), "Host": "api.live.bilibili.com", "Referer": "http://live.bilibili.com/" + self.config.get('roomId'), "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0" } } self.sendLock = False def get(self): # 准备数据 roomId = self.config.get('roomId') postData = urllib.parse.urlencode({ 'token:': '', 'csrf_token:': '', 'roomid': roomId }).encode('utf-8') # 发送请求 request = urllib.request.Request(self.httpConfig['getUrl'], postData, self.httpConfig['header']) response = json.loads( urllib.request.urlopen(request).read().decode('utf-8')) # 获取最后的弹幕时间 configTimestamp = self.config.get(module='danmu', key='timestamp') if configTimestamp == None: configTimestamp = 0 else: configTimestamp = float(configTimestamp) if 'code' in response and response['code'] == 0: # 解析弹幕 result = [] for danmu in response['data']['room']: # 判断弹幕是否被处理过 thisTimestamp = time.mktime( time.strptime(danmu['timeline'], "%Y-%m-%d %H:%M:%S")) if configTimestamp >= thisTimestamp: continue self.config.set(module='danmu', key='timestamp', value=thisTimestamp) result.append({ 'name': danmu['nickname'], 'time': danmu['timeline'], 'uid': str(danmu['uid']), 'text': danmu['text'] }) pass return result else: raise Exception('Cookie 无效') #发送弹幕函数 def send(self, text): elapsedTime = 0 while self.sendLock: time.sleep(1) # 判断等待超时 elapsedTime += 1 if (elapsedTime > 30): return None # 判断长度 lengthLimit = 20 if len(text) > lengthLimit: for i in range(0, len(text), lengthLimit): self.send(text[i:i + lengthLimit]) time.sleep(1.5) return True # 准备数据 self.sendLock = True try: roomId = self.config.get('roomId') csrf = self.config.get('csrf') postData = (urllib.parse.urlencode({ 'color': '16777215', 'fontsize': '25', 'mode': '1', 'msg': text, 'rnd': '1616330701', 'roomid': roomId, 'csrf_token': csrf, 'csrf': csrf }).encode('utf-8')) # 发送请求 request = urllib.request.Request(self.httpConfig['sendUrl'], postData, self.httpConfig['header']) response = json.loads( urllib.request.urlopen(request).read().decode('utf-8')) print(response) print("发送弹幕结束,弹幕 " + text) return 'code' in response and response['code'] == 0 except Exception as e: raise e finally: self.sendLock = False
def __init__(self, board, parent=None): QWidget.__init__(self, parent) config = Config("config/config.conf") self.b = board # boolean qui permet d'eviter un double appel par keyPressEvent self.changeSong = True path = config.getValueOf("path") if path and os.path.exists(path): self.b.setDirectory(path) else: config.deleteConfig("path") config.save() # zone de recherche a gauche self.searchSong = SearchSong(self.b) # liste d'attente prioritaire self.textLabelPrimary = "Liste d'attente prioritaire" self.labPrimary = QLabel(self.textLabelPrimary) self.labPrimary.setProperty("class", "title") self.labPrimary.setAlignment(Qt.AlignCenter) self.primaryQueue = QueueSong(self.b, self.b.getPrimaryQueue, self.b.getSecondaryQueue) # liste d'attente secondaire labSecondary = QLabel("Liste d'attente") labSecondary.setProperty("class", "title") labSecondary.setAlignment(Qt.AlignCenter) self.secondaryQueue = QueueSong(self.b, self.b.getSecondaryQueue, self.b.getPrimaryQueue) self.b.addListener(self.primaryQueue) self.b.addListener(self.secondaryQueue) # partie lecteur en bas self.player = PlayerSound(self.b) self.b.addListener(self.player) # disposition layout = QVBoxLayout() self.setLayout(layout) queueSongs = QHBoxLayout() queueSongs.addWidget(self.searchSong) primaryQueueLayout = QVBoxLayout() primaryQueueLayout.addWidget(self.labPrimary) primaryQueueLayout.addWidget(self.primaryQueue) secondaryQueueLayout = QVBoxLayout() secondaryQueueLayout.addWidget(labSecondary) secondaryQueueLayout.addWidget(self.secondaryQueue) queueSongs.addLayout(primaryQueueLayout) queueSongs.addLayout(secondaryQueueLayout) layout.addLayout(queueSongs) layout.addWidget(self.player) self.b.addListener(self)
def __init__(self): all_config = Config() self.headers = { 'User-Agent': all_config.get(key='User-Agent', module='headers'), 'Cookie': all_config.get(key='Cookie', module='headers') }