Dataset Viewer
Auto-converted to Parquet Duplicate
repo_name
string
branch_name
string
path
string
content
string
context
string
import_relationships
dict
0-1-0/marketbot
refs/heads/master
/tests.py
import utils import pymongo import unittest class MailerTestCase(unittest.TestCase): def test_basic(self): db = pymongo.MongoClient()['marketbot'] order = list(db.orders.find({}))[-1] resp = utils.Mailer().send_order('marketbottest@gmail.com', order) self.assertEquals(resp.status_code, 202)
# -*- coding: utf-8 -*- import sendgrid import os from sendgrid.helpers.mail import * import re import requests import json WED_ADMIN_DOMAIN = open('domain').read().split('\n')[0] def get_address(lat, lng): resp = requests.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + str(lat) + ',' + str(lng) + '&language=ru') return json.loads(resp.content).get('results')[0].get('formatted_address') class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class Mailer(Singleton): sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) def send(self, mail, subj, txt): from_email = Email("order@botmarket.com") subject = subj to_email = Email(mail) content = Content("text/plain", txt) mail = Mail(from_email, subject, to_email, content) return self.sg.client.mail.send.post(request_body=mail.get()) def send_order(self, mail, order): res = 'Заказ\n====\n\n\n' res += '\n'.join(i['name'].encode('utf-8') + ' x ' + str(i['count']) for i in order['items']) res += '\n-----\n Итого: ' + str(order['total']) + ' руб.' res += '\n-----\n Детали доставки: \n' try: res += '\n\n'.join(k.encode('utf-8') + ': ' + v.encode('utf-8') for k, v in order['delivery'].items()) except: res += '\n\n'.join(k + ': ' + v for k, v in order['delivery'].items()) res = res.replace('Ваш', '') return self.send(mail, 'Новый заказ!', res) def striphtml(data): p = re.compile(r'<[brai].*?>|<\/[a].*?>|<span.*?>|<\/span.*?>') res = p.sub('\n', data) return res.replace('&nbsp;', ' ').replace('&mdash;', '-')
{ "imports": [ "/utils.py" ] }
0-1-0/marketbot
refs/heads/master
/webhook_listener.py
from gevent import monkey; monkey.patch_all() import web from web.wsgiserver import CherryPyWSGIServer from app import MasterBot CherryPyWSGIServer.ssl_certificate = "/home/ubuntu/webhook_cert.pem" CherryPyWSGIServer.ssl_private_key = "/home/ubuntu/webhook_pkey.pem" urls = ("/.*", "hello") app = web.application(urls, globals()) mb = MasterBot({'token': open('token').read().replace('\n', '')}) class hello: def POST(self): token = web.ctx.path.split('/')[1] mb.route_update(token, web.data()) return 'ok' if __name__ == "__main__": app.run()
# -*- coding: utf-8 -*- import gevent from gevent import monkey; monkey.patch_all() import telebot from telebot import apihelper from pymongo import MongoClient from views import * from utils import get_address import botan import time botan_token = 'BLe0W1GY8SwbNijJ0H-lroERrA9BnK0t' class Convo(object): def __init__(self, data, bot): self.bot = bot self.token = bot.token self.db = bot.db self.chat_id = data['chat_id'] self.views = {} self.path = data.get('path') self.tmpdata = None def get_current_view(self): if self.path and self.path[0] in self.views: return self.views[self.path[0]].route(self.path[1:]) return None def get_bot_data(self): return self.db.bots.find_one({'token': self.token}) def _send_msg(self, msg1, markup): try: apihelper.send_message(self.token, self.chat_id, msg1, reply_markup=markup, parse_mode='HTML') except Exception, e: self.bot.log_error({'func': '_send_msg', 'token': self.token, 'chat_id': self.chat_id, 'message': msg1, 'error': str(e)}) def send_message(self, msg, markup=None): if self.chat_id: msg1 = msg.replace('<br />', '.\n') gevent.spawn(self._send_msg, msg1, markup) return def edit_message(self, message_id, msg, markup=None): if self.chat_id: msg1 = msg.replace('<br />', '.\n') gevent.spawn(apihelper.edit_message_text, self.token, msg1, self.chat_id, message_id=message_id, reply_markup=markup, parse_mode='HTML') return def process_message(self, message): try: txt = message.text.encode('utf-8') except: if hasattr(message, 'contact') and message.contact is not None: txt = message.contact.phone_number if hasattr(message, 'location') and message.location is not None: txt = get_address(message.location.latitude, message.location.longitude).encode('utf-8') if txt: self.send_message(txt) self.get_current_view().process_message(txt) def process_photo(self, photo): self.get_current_view().process_photo(photo) def process_sticker(self, sticker): self.get_current_view().process_sticker(sticker) def process_video(self, video): self.get_current_view().process_video(video) def process_callback(self, callback): self.get_current_view().process_callback(callback) def process_file(self, doc): self.get_current_view().process_file(doc) def set_path(self, path): self.path = path gevent.spawn(self.db.convos.update_one, {'bot_token': self.bot.token, 'chat_id': self.chat_id}, {'$set': {'path': path}}) def route(self, path): self.set_path(path) self.get_current_view().activate() class MarketBotConvo(Convo): def __init__(self, data, bot): super(MarketBotConvo, self).__init__(data, bot) self.current_basket = None self.views['delivery'] = OrderCreatorView(self, [], final_message='Заказ сформирован!') self.views['menu_cat_view'] = MenuCatView(self, msg="Выберите категорию:") self.views['order_info'] = OrderInfoView(self, msg="Тут должны быть условия доставки", links={'Главное меню': ['main_view']}) self.views['contacts'] = ContactsInfoView(self, links={'Главное меню': ['main_view']}) self.views['history'] = HistoryView(self) self.views['main_view'] = NavigationView(self, links={ "Меню": ['menu_cat_view'], "История": ['history'], "Доставка": ['order_info'], # , "Контакты": ['contacts'] # ContactsInfoView(self.ctx) }, msg="Главное меню") self.path = data.get('path') if not self.get_current_view(): self.route(['main_view']) class MainConvo(Convo): def __init__(self, data, bot): super(MainConvo, self).__init__(data, bot) self.views['main_view'] = NavigationView( self, links={ "Добавить магазин": ['add_view'], "Настройки": ['settings_view'], "Заказы": ['orders_view'], "Помощь": ['help_view'], "Рассылка новостей": ['mailing_view'] }, msg="Главное меню" ) self.views['help_view'] = HelpView(self, links={'Назад': ['main_view']}) self.views['add_view'] = BotCreatorView(self, [ TokenDetail('shop.token', name='API token.', desc='Для этого перейдите в @BotFather и нажмите /newbot для создания бота. Придумайте название бота (должно быть на русском языке) и ссылку на бот (на английском языке и заканчиваться на bot). Далее вы увидите API token, который нужно скопировать и отправить в этот чат.', ctx=self), EmailDetail('shop.email', name='email для приема заказов', ctx=self), FileDetail('shop.items', name='файл с описанием товаров или url магазина вконтакте', desc='<a href="https://github.com/0-1-0/marketbot/blob/master/sample.xlsx?raw=true">Пример файла</a>'), TextDetail('shop.delivery_info', name='текст с условиями доставки'), TextDetail('shop.contacts_info', name='текст с контактами для связи', value='telegram: @' + str(self.bot.bot.get_chat(self.chat_id).username)), NumberDetail('shop.total_threshold', name='минимальную сумму заказа', value='0') ], final_message='Магазин создан!') self.views['settings_view'] = SelectBotView(self, bot_view={'link': 'settings_view', 'view': SettingsView}) self.views['orders_view'] = SelectBotView(self, bot_view={'link': 'orders_view', 'view': OrdersView}) self.views['mailing_view'] = SelectBotView(self, bot_view={'link': 'mailing_view', 'view': MailingView}) self.path = data.get('path') if not self.get_current_view(): self.route(['main_view']) class Bot(object): bots = {} WEBHOOK_HOST = 'ec2-52-34-35-240.us-west-2.compute.amazonaws.com' WEBHOOK_PORT = 8443 WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT) WEBHOOK_SSL_CERT = '/home/ubuntu/webhook_cert.pem' def __init__(self, token): self.token = token Bot.bots[self.token] = self gevent.spawn(self.set_webhook, self.token) def log_error(self, e): pass def set_webhook(self, token, retries=0): try: bot = telebot.TeleBot(token) bot.remove_webhook() bot.set_webhook(url=self.WEBHOOK_URL_BASE + '/' + bot.token + '/', certificate=open(self.WEBHOOK_SSL_CERT, 'r')) print token, 'registered' except Exception, e: self.log_error(e) print token, e if retries < 2: time.sleep(1) self.set_webhook(token, retries+1) class MarketBot(Bot): convo_type = MarketBotConvo def __init__(self, data, db=MongoClient()['marketbot']): super(MarketBot, self).__init__(data['token']) self.convos = {} self.db = db if not self.db.bots.update_one({'token': self.token}, {'$set': apihelper.get_me(self.token)}): self.db.bots.insert_one({'token': self.token}) self.email = data.get('email') self.last_update_id = data.get('last_update_id') or 0 self._init_bot() for convo_data in self.db.convos.find({'bot_token': self.token}): self.init_convo(convo_data) def log_error(self, e): gevent.spawn(self.db.errors.insert_one, {'error': str(e)}) def _init_bot(self, threaded=False): self.bot = telebot.TeleBot(self.token, threaded=threaded, skip_pending=True) self.bot.add_message_handler(self.goto_main, commands=['start']) self.bot.add_callback_query_handler(self.process_callback, func=lambda call: True) self.bot.add_message_handler(self.process_photo, content_types=['photo']) self.bot.add_message_handler(self.process_video, content_types=['video']) self.bot.add_message_handler(self.process_sticker, content_types=['sticker']) self.bot.add_message_handler(self.process_file, content_types=['document']) self.bot.add_message_handler(self.process_message, func=lambda message: True, content_types=['text', 'contact', 'location']) def init_convo(self, convo_data): self.convos[convo_data['chat_id']] = self.convo_type(convo_data, self) def get_convo(self, chat_id): if chat_id not in self.convos: convo_data = {'chat_id': chat_id, 'bot_token': self.token} self.db.convos.insert_one(convo_data) self.init_convo(convo_data) return self.convos[chat_id] def goto_main(self, message): convo = self.get_convo(message.chat.id) convo.route(['main_view']) def process_callback(self, callback): convo = self.get_convo(callback.message.chat.id) gevent.spawn(convo.process_callback, callback) def process_message(self, message): convo = self.get_convo(message.chat.id) gevent.spawn(convo.process_message, message) def start_bot(self, bot_data): MarketBot(bot_data, self.db) def process_file(self, doc): convo = self.get_convo(doc.chat.id) convo.process_file(doc) def process_sticker(self, sticker): convo = self.get_convo(sticker.chat.id) convo.process_sticker(sticker) def process_video(self, video): convo = self.get_convo(video.chat.id) convo.process_video(video) def process_photo(self, photo): convo = self.get_convo(photo.chat.id) gevent.spawn(convo.process_photo, photo) def update_last_id(self): self.db.bots.update_one({'token': self.token}, {'$set': {'last_update_id': self.last_update_id}}) def process_redis_update(self, update): if isinstance(update, basestring): update = telebot.types.Update.de_json(update.encode('utf-8')) if update.update_id > self.last_update_id: self.last_update_id = update.update_id gevent.spawn(self.bot.process_new_updates, [update]) gevent.spawn(self.update_last_id) class MasterBot(MarketBot): convo_type = MainConvo def process_message(self, message): gevent.spawn(botan.track, botan_token, message.chat.id, {'from_user': message.from_user.username}, message.text) super(MasterBot, self).process_message(message) def __init__(self, data): super(MasterBot, self).__init__(data) for bot_data in self.db.bots.find(): if bot_data['token'] != self.token: try: MarketBot(bot_data, self.db) except Exception, e: self.log_error(e) def route_update(self, token, update): if token in Bot.bots: gevent.spawn(Bot.bots[token].process_redis_update, update) return if __name__ == "__main__": m = MasterBot({'token': open('token').read().replace('\n', '')}) gevent.spawn(m.run).join()
{ "imports": [ "/app.py" ] }
0-1-0/marketbot
refs/heads/master
/views.py
# -*- coding: utf-8 -*- import gevent from gevent import monkey; monkey.patch_all() from telebot import types import telebot from telebot import apihelper from validate_email import validate_email import pymongo from io import BytesIO from StringIO import StringIO from datetime import datetime from utils import Mailer, striphtml, WED_ADMIN_DOMAIN from collections import defaultdict from vk_crawler import Crawler from pyexcel_xls import get_data import pandas as pd import md5 from time import time class MarkupMixin(object): def mk_markup(self, command_list): markup = types.ReplyKeyboardMarkup(row_width=2) btns = [self.BTN(cmd) for cmd in command_list] for btn in btns[:min(3, len(btns))]: markup.row(btn) markup.add(*btns[3:]) return markup def BTN(self, txt, request_contact=None, request_location=None): return types.KeyboardButton(txt, request_contact=request_contact, request_location=request_location) def mk_inline_markup(self, command_list): markup = types.InlineKeyboardMarkup(row_width=2) btns = [types.InlineKeyboardButton(cmd, callback_data=cmd) for cmd in command_list] for btn in btns: markup.row(btn) return markup def btn(self, txt, callback_data): return types.InlineKeyboardButton(txt, callback_data=callback_data) class View(MarkupMixin): def __init__(self, ctx, editable=True, msg=''): self.ctx = ctx self.editable = editable self.active = False self.message_id = None self.msg = msg self.views = {} def route(self, path): if path == []: return self else: return self.get_subview(path[0]).route(path[1:]) def get_subview(self, _id): return self.views.get(_id) or self def process_message(self, message): pass def process_callback(self, callback): pass def process_photo(self, photo): pass def process_file(self, doc): pass def process_sticker(self, sticker): pass def process_video(self, video): pass def activate(self): self.deactivate() for v in self.ctx.views.values(): v.deactivate() self.active = True self.render() def deactivate(self): self.active = False self.message_id = None def get_msg(self): return self.msg def get_markup(self): return None def render(self): if not (self.editable and self.message_id): self.ctx.send_message(self.get_msg(), self.get_markup()) else: self.ctx.edit_message(self.message_id, self.get_msg(), self.get_markup()) class NavigationView(View): def __init__(self, ctx, links={}, msg=""): self.links = links super(NavigationView, self).__init__(ctx, False, msg) def get_markup(self): return self.mk_markup(sorted([l.decode('utf-8') for l in self.links.keys()])) def process_message(self, message): if message in self.links: self.ctx.route(self.links[message]) class InlineNavigationView(NavigationView): def get_markup(self): markup = types.InlineKeyboardMarkup(row_width=2) for k in self.links.keys(): markup.row(self.btn(k, callback_data=k)) return markup def process_callback(self, callback): cmd = callback.data self.message_id = callback.message.message_id self.process_message(cmd) class OrderView(View): def __init__(self, ctx, data): self.ctx = ctx self.data = data self.editable = True self.message_id = None def get_msg(self): res = 'Заказ #' + str(self.data['number']) + '\n' res += 'Статус: ' + self.data['status'].encode('utf-8') + '\n' res += '\n'.join(i['name'].encode('utf-8') + ' x ' + str(i['count']) for i in self.data['items']) res += '\n-----\n Итого: ' + str(self.data['total']) + ' руб.' res += '\n-----\n Детали доставки: \n' res += '\n\n'.join(k.encode('utf-8') + ': ' + v.encode('utf-8') for k, v in self.data['delivery'].items()) res = res.replace('Ваш', '') return res def get_markup(self): markup = types.InlineKeyboardMarkup(row_width=2) if self.data['status'] == u'В обработке': markup.row(self.btn(u'Завершить', str(self.data['number']) + ':complete')) else: markup.row(self.btn(u'Перенести в обработку', str(self.data['number']) + ':reactivate')) return markup def process_callback(self, callback): action = callback.data.split(':')[1] self.message_id = callback.message.message_id if action == 'complete': self.ctx.db.orders.update_one({'_id': self.data['_id']}, {'$set': {'status': 'Завершен'}}) self.data = self.ctx.db.orders.find_one({'_id': self.data['_id']}) self.render() elif action == 'reactivate': self.ctx.db.orders.update_one({'_id': self.data['_id']}, {'$set': {'status': 'В обработке'}}) self.data = self.ctx.db.orders.find_one({'_id': self.data['_id']}) self.render() class AdminOrderView(View): def __init__(self, ctx, bot_token, status=u'В обработке'): self.ctx = ctx self.token = bot_token self.editable = True self.status = status self.orders = [OrderView(self.ctx, o) for o in self.ctx.db.orders.find({'token': self.token, 'status': status}).sort('date', pymongo.DESCENDING)] self._orders = {} for o in self.orders: self._orders[str(o.data['number'])] = o def render(self): if len(self.orders) > 0: self.ctx.send_message('Заказы', markup=self.mk_markup(['Еще 5', 'Главное меню'])) else: self.ctx.send_message('Нет заказов', markup=self.mk_markup(['Главное меню'])) self.ptr = 0 self.render_5() def render_5(self): for order in self.orders[self.ptr: self.ptr + 5]: order.render() self.ptr += 5 def process_message(self, message): if message == 'Главное меню': self.ctx.route(['main_view']) elif message == 'Еще 5': self.render_5() def process_callback(self, callback): data = callback.data.encode('utf-8') number, action = data.split(':') self._orders[number].process_callback(callback) class DetailsView(View): def __init__(self, ctx, details, final_message=""): self.ctx = ctx self.details = details self.ptr = 0 self.editable = False self.filled = False self.final_message = final_message def activate(self): self.filled = False for d in self.details: d.value = None self.ptr = 0 super(DetailsView, self).activate() def details_dict(self): return {d._id: d.value for d in self.details} def prefinalize(self): pass def finalize(self): pass def current(self): return self.details[self.ptr] def get_msg(self): if self.filled: res = self.final_message + '\n' if not isinstance(self, BotCreatorView): # TODO /hack for d in self.details: res += (d.name + ": " + d.txt() + '\n') return res else: res = 'Укажите ' + self.current().name if self.current().is_filled(): try: res += '\n(Сейчас: ' + self.current().value + ' )' except: try: res += '\n(Сейчас: ' + self.current().value.encode('utf-8') + ' )' except: pass res += '\n' + self.current().desc return res def get_markup(self): if not self.filled: markup = types.ReplyKeyboardMarkup() if self.current().is_filled() or isinstance(self.current(), FileDetail): markup.row(self.BTN('ОК')) if self.current()._id == 'phone': markup.row(self.BTN('отправить номер', request_contact=True)) if self.current()._id == 'address': markup.row(self.BTN('отправить геолокацию', request_location=True)) if len(self.current().default_options) > 0: markup.row(*[self.BTN(opt) for opt in self.current().default_options]) if self.ptr > 0: markup.row(self.BTN('Назад')) markup.row(self.BTN('Главное меню')) return markup else: return None def next(self): if self.ptr + 1 < len(self.details): if self.current().is_filled(): self.ptr += 1 self.render() else: self.filled = True self.prefinalize() self.render() self.ctx.route(['main_view']) self.finalize() def prev(self): if self.ptr > 0: self.ptr -= 1 self.render() def analyze_vk_link(self, url): self.ctx.tmpdata = Crawler(url).fetch() self.process_message('ОК') def process_message(self, cmd): if cmd == 'ОК': if isinstance(self.current(), FileDetail) and self.ctx.tmpdata is not None: if self.current().validate(self.ctx.tmpdata): self.current().value = self.ctx.tmpdata self.ctx.tmpdata = None self.next() else: self.ctx.send_message('Неверный формат файла') elif self.current().is_filled(): self.next() else: self.render() elif cmd == 'Назад': self.prev() elif cmd == 'Главное меню': self.ctx.route(['main_view']) elif isinstance(self.current(), TextDetail): if self.current().validate(cmd): self.current().value = cmd self.next() else: self.ctx.send_message('Неверный формат') elif isinstance(self.current(), NumberDetail): if self.current().validate(cmd): self.current().value = cmd self.next() else: self.ctx.send_message('Введите целое число') elif isinstance(self.current(), FileDetail): if 'vk.com' in cmd: try: gevent.spawn(self.analyze_vk_link, cmd) self.ctx.send_message('Анализирую..') self.ctx.tmpdata = None except Exception: self.ctx.send_message('Неверный формат магазина') class BotCreatorView(DetailsView): def prefinalize(self): self._final_message = self.final_message self.final_message += '\n Ссылка на бота: @' + telebot.TeleBot(self.details_dict().get('shop.token') or self.token).get_me().username.encode('utf-8') def bot_data(self): dd = self.details_dict() link = md5.new() link.update(dd['shop.token'] + dd['shop.token'][::-1]) return { 'admin': self.ctx.bot.bot.get_chat(self.ctx.chat_id).username, 'token': dd['shop.token'], 'items': dd['shop.items'], 'email': dd['shop.email'], 'chat_id': self.ctx.chat_id, 'delivery_info': dd['shop.delivery_info'], 'contacts_info': dd['shop.contacts_info'], 'total_threshold': dd['shop.total_threshold'], 'link': link.hexdigest() } def finalize(self): self.final_message = self._final_message bot_data = self.bot_data() self.ctx.db.bots.save(bot_data) self.ctx.bot.start_bot(bot_data) def process_file(self, doc): fid = doc.document.file_id file_info = self.ctx.bot.bot.get_file(fid) file_format = file_info.file_path.split('.')[-1] if file_format in ['csv', 'xls', 'xlsx']: content = self.ctx.bot.bot.download_file(file_info.file_path) io = StringIO(content) try: df = pd.read_csv(io) except: excel_data = get_data(io) _keys = excel_data.values()[0][0] _values = excel_data.values()[0][1:] _items = [dict(zip(_keys, rec)) for rec in _values] df = pd.DataFrame(_items) df_keys = {k.lower(): k for k in df.to_dict().keys()} data = pd.DataFrame() mapping = { 'id': ['id', 'product_id'], 'active': ['active', 'visible', u'активно'], 'cat': ['category', u'раздел 1', u'категория'], 'name': [u'наименование', 'name'], 'desc': [u'описание', 'description', 'description(html)'], 'price': ['price', u'цена'], 'img': ['img_url', u'изображение', u'ссылка на изображение'] } for k, values in mapping.items(): for col_name in values: if col_name in df_keys: data[k] = df[df_keys[col_name]] data['active'] = data['active'].map(lambda x: '1' if x in [1, 'y'] else '0') items = data.T.to_dict().values() if len(items) == 0: raise Exception("no items added") self.ctx.tmpdata = items else: pass class ItemNode(View): def __init__(self, menu_item, _id, ctx, menu): self.editable = True self.description = menu_item['desc'] self.img = menu_item['img'] self.count = 0 self.message_id = None self.price = int(menu_item['price']) self.name = menu_item['name'] self._id = _id self.ctx = ctx self.ordered = False self.menu = menu self.menu_item = menu_item def to_dict(self): return dict(self.menu_item.items() + {'count': self.count}.items()) def get_btn_txt(self): res = str(self.price) + ' руб.' if self.count > 0: res += ' ' + str(self.count) + ' шт.' return res def get_add_callback(self): return 'menu_item:' + str(self._id) + ':add' def get_basket_callback(self): return 'menu_item:' + str(self._id) + ':basket' def sub(self): self.count -= 1 self.render() def add(self): self.count += 1 self.render() def get_markup(self): markup = types.InlineKeyboardMarkup() markup.row(types.InlineKeyboardButton(self.get_btn_txt(), callback_data=self.get_add_callback())) if self.count > 0: markup.row(types.InlineKeyboardButton('Добавить в корзину', callback_data=self.get_basket_callback())) return markup def get_total(self): return self.count * self.price def get_msg(self): return (u'<a href="' + self.img + u'">' + self.name + u'</a>\n' + striphtml(self.description))[:500] def process_callback(self, call): self.message_id = call.message.message_id _id, action = call.data.split(':')[1:] if action == 'add': self.count += 1 self.render() if action == 'basket': self.ordered = True self.menu.goto_basket(call) class BasketNode(View): def __init__(self, menu): self.menu = menu self.chat_id = menu.ctx.chat_id self.message_id = None self.ctx = menu.ctx self.items = [] self.item_ptr = 0 self.editable = True self.ctx.current_basket = self def to_dict(self): return { 'chat_id': self.chat_id, 'items': [i.to_dict() for i in self.items if i.count > 0], 'total': self.get_total() } def get_ordered_items(self): return filter(lambda i: i.ordered is True, self.menu.items.values()) def activate(self): self.items = list(set(self.items + self.get_ordered_items())) self.total_threshold = int(self.ctx.get_bot_data().get('total_threshold') or 0) self.item_ptr = 0 def current_item(self): return self.items[self.item_ptr] def inc(self): if self.item_ptr + 1 < len(self.items): self.item_ptr += 1 self.render() def dec(self): if self.item_ptr - 1 > -1: self.item_ptr -= 1 self.render() def add(self): self.current_item().add() self.render() def sub(self): if self.current_item().count > 0: self.current_item().sub() self.render() def get_total(self): return sum(i.get_total() for i in self.items) def __str__(self): res = "" for item in self.items: if item.count > 0: res += item.name.encode('utf-8') + " " + str(item.count) + "шт. " + str(self.current_item().get_total()) + ' руб\n' res += 'Итого: ' + str(self.get_total()) + 'руб.' return res def get_msg(self): if self.get_total() > 0: res = 'Корзина:' + '\n\n' res += self.current_item().get_msg().encode('utf-8') + '\n' res += str(self.current_item().price) + ' * ' + str(self.current_item().count) + ' = ' + str(self.current_item().get_total()) + ' руб' return res else: return 'В Корзине пусто' def process_callback(self, call): self.message_id = call.message.message_id action = call.data.split(':')[-1] if action == '>': self.inc() elif action == '<': self.dec() elif action == '+': self.add() elif action == '-': self.sub() elif action == '<<': self.ctx.send_message('Минимальная сумма заказа ' + str(self.total_threshold) + ' рублей') def get_markup(self): if self.get_total() > 0: markup = types.InlineKeyboardMarkup() markup.row( self.btn('-', 'basket:-'), self.btn(str(self.current_item().count) + ' шт.', 'basket:cnt'), self.btn('+', 'basket:+') ) markup.row(self.btn('<', 'basket:<'), self.btn(str(self.item_ptr + 1) + '/' + str(len(self.items)), 'basket:ptr'), self.btn('>', 'basket:>')) if self.get_total() < self.total_threshold: markup.row(self.btn('Минимальная сумма заказа ' + str(self.total_threshold) + ' рублей', 'basket:<<')) else: markup.row(self.btn('Заказ на ' + str(self.get_total()) + ' р. Оформить?', 'link:delivery')) return markup else: return None class MenuNode(View): def __init__(self, msg, menu_items, ctx, links, parent=None): self.ctx = ctx self.msg = msg self.items = {} self.basket = self.ctx.current_basket or BasketNode(self) self.links = links self.ptr = 0 self.editable = False self.parent = parent self.message_id = None cnt = 0 for item in menu_items: try: _id = str(cnt) self.items[_id] = ItemNode(item, _id, self.ctx, self) cnt += 1 except Exception: pass def render(self): super(MenuNode, self).render() self.render_5() def render_5(self): for item in self.items.values()[self.ptr:self.ptr + 5]: try: item.render() except Exception: pass self.ptr += 5 def process_message(self, message): txt = message if txt == 'Показать еще 5': self.render() elif txt == 'Назад': self.ctx.route(['menu_cat_view']) def get_msg(self): return self.msg def get_markup(self): if self.ptr + 6 < len(self.items): return self.mk_markup(['Показать еще 5', 'Назад']) else: return self.mk_markup(['Назад']) def process_callback(self, call): # route callback to item node self.message_id = call.message.message_id data = call.data.encode('utf-8') _type = data.split(':')[0] if _type == 'menu_item': node_id = data.split(':')[1] if node_id in self.items: self.items[node_id].process_callback(call) elif _type == 'basket': self.basket.process_callback(call) elif _type == 'link': ll = data.split(':')[1] if ll in self.links: self.ctx.route(self.links[ll]) def goto_basket(self, call): self.basket.menu = self self.basket.message_id = None self.basket.activate() self.basket.render() class OrderCreatorView(DetailsView): def __init__(self, ctx, details, final_message=""): super(OrderCreatorView, self).__init__(ctx, details, final_message) self.orders = list(self.ctx.db.orders.find({'token': self.ctx.bot.token, 'chat_id': self.ctx.chat_id}).sort('date', pymongo.DESCENDING)) if len(self.orders) > 0: last_order = self.orders[0]['delivery'] else: last_order = {} def _get(v): try: return last_order.get(v.decode('utf-8')).encode('utf-8') except: return last_order.get(v.decode('utf-8')) self.details = [ TextDetail('delivery_type', ['Доставка до дома', 'Самовывоз'], name='тип доставки', ctx=self.ctx, value=_get('тип доставки')), TextDetail('address', name='Ваш адрес', ctx=self.ctx, value=_get('Ваш адрес')), TextDetail('phone', name='Ваш телефон', ctx=self.ctx, value=_get('Ваш телефон')), TextDetail('delivery_time', name='желаемое время доставки', ctx=self.ctx) ] def activate(self): self.filled = False self.ptr = 0 super(DetailsView, self).activate() def finalize(self): order = self.ctx.current_basket.to_dict() order['delivery'] = {} for d in self.details: order['delivery'][d.name] = d.txt() order['date'] = datetime.utcnow() order['status'] = 'В обработке' order['token'] = self.ctx.token order['number'] = len(self.orders) self.ctx.db.orders.insert_one(order) gevent.spawn(Mailer().send_order, self.ctx.get_bot_data()['email'], order) self.ctx.current_basket = None class UpdateBotView(BotCreatorView): def __init__(self, ctx, token, details, final_message=""): self.token = token super(UpdateBotView, self).__init__(ctx, details, final_message=final_message) def activate(self): self.filled = False self.ptr = 0 super(DetailsView, self).activate() def get_markup(self): markup = types.ReplyKeyboardMarkup() if isinstance(self.current(), FileDetail): markup.row(self.BTN('ОК')) if self.current()._id == 'phone': markup.row(self.BTN('отправить номер', request_contact=True)) if self.current()._id == 'address': markup.row(self.BTN('отправить геолокацию', request_location=True)) if len(self.current().default_options) > 0: markup.row(*[self.BTN(opt) for opt in self.current().default_options]) markup.row(self.BTN('Назад')) return markup def process_message(self, cmd): if cmd == 'ОК': if isinstance(self.current(), FileDetail) and self.ctx.tmpdata is not None: if self.current().validate(self.ctx.tmpdata): self.current().value = self.ctx.tmpdata self.ctx.tmpdata = None self.next() else: self.ctx.send_message('Неверный формат файла') elif self.current().is_filled(): self.finalize() self.ctx.route(['settings_view', self.token]) else: self.render() elif cmd == 'Назад': self.ctx.route(['settings_view', self.token]) elif cmd == 'Главное меню': self.ctx.route(['main_view']) elif isinstance(self.current(), TextDetail): if self.current().validate(cmd): self.current().value = cmd self.finalize() self.ctx.route(['settings_view', self.token]) else: self.ctx.send_message('Неверный формат') elif isinstance(self.current(), NumberDetail): if self.current().validate(cmd): self.current().value = cmd self.finalize() self.ctx.route(['settings_view', self.token]) else: self.ctx.send_message('Введите целое число') elif isinstance(self.current(), FileDetail): if 'vk.com' in cmd: try: # self.ctx.redis.publish('vk_input', json.dumps({'token': self.ctx.token, 'chat_id': self.ctx.chat_id, 'url': cmd})) gevent.spawn(self.analyze_vk_link, cmd) self.ctx.send_message('Анализирую..') self.ctx.tmpdata = None except Exception: self.ctx.send_message('Неверный формат магазина') def finalize(self): self.ctx.db.bots.update_one({'token': self.token}, {'$set': {self.current()._id.split('.')[-1]: self.current().value}}) class MenuCatView(InlineNavigationView): def __init__(self, ctx, msg=''): super(MenuCatView, self).__init__(ctx, msg=msg) self.init_categories() def activate(self): self.init_categories() super(MenuCatView, self).activate() def init_categories(self): data = self.ctx.get_bot_data()['items'] self.categories = defaultdict(list) for item_data in data: self.categories[item_data['cat'].split('.')[0][:80]].append(item_data) # TODO HACK if u'' in self.categories: del self.categories[u''] self.links = {cat: ['menu_cat_view', cat] for cat in self.categories.keys()} self.views = {cat: MenuNode(cat, items, self.ctx, links={"delivery": ['delivery']}) for cat, items in self.categories.items()} def process_message(self, cmd): if cmd == 'Назад' or cmd == 'Главное меню': self.ctx.route(['main_view']) else: super(MenuCatView, self).process_message(cmd) def route(self, path): if path == []: self.views = {cat: MenuNode(cat, items, self.ctx, links={"delivery": ['delivery']}) for cat, items in self.categories.items()} return super(MenuCatView, self).route(path) def render(self): self.ctx.send_message('Меню', markup=self.mk_markup(['Назад'])) super(MenuCatView, self).render() class OrderInfoView(NavigationView): def get_msg(self): return self.ctx.get_bot_data().get('delivery_info') or 'Об условиях доставки пишите: @' + self.ctx.get_bot_data().get('admin') class ContactsInfoView(NavigationView): def get_msg(self): return self.ctx.get_bot_data().get('contacts_info') or 'Чтобы узнать подробности свяжитесь с @' + self.ctx.get_bot_data().get('admin') class HistoryItem(object): def __init__(self, order): self.order = order def __str__(self): res = str(self.order.get('date')).split('.')[0] + '\n\n' res += '\n'.join(i['name'].encode('utf-8') + ' x ' + str(i['count']) for i in self.order['items']) res += '\n-----\n Итого: ' + str(self.order['total']) + ' руб.' res += '\n-----\n Детали доставки: \n-----\n' try: res += '\n'.join(k.encode('utf-8') + ': ' + v.encode('utf-8') for k, v in self.order['delivery'].items()) except: try: res += '\n'.join(k + ': ' + v for k, v in self.order['delivery'].items()) except: pass return res class HistoryView(NavigationView): def activate(self): self.cursor = 0 self.orders = list(self.ctx.db.orders.find({'token': self.ctx.bot.token, 'chat_id': self.ctx.chat_id}).sort('date', pymongo.DESCENDING)) self.links = { 'Главное меню': ['main_view'] } if len(self.orders) > 0: self.links['Еще 5'] = ['history'] super(HistoryView, self).activate() def render_5(self): for order in self.orders[self.cursor:self.cursor + 5]: self.ctx.send_message(str(HistoryItem(order))) self.cursor += 5 def process_message(self, message): if message == 'Еще 5': self.render_5() if message == 'Главное меню': self.ctx.route(['main_view']) def get_msg(self): if len(self.orders) > 0: self.render_5() return ':)' else: return 'История заказов пуста' class SelectBotView(NavigationView): def __init__(self, ctx, links={}, msg="Выберите бота:", bot_view=None): self.ctx = ctx self.links = links self.msg = msg self.bot_view = bot_view super(NavigationView, self).__init__(ctx, False, msg) def get_subview(self, token): if token not in self.views: self.views[token] = self.bot_view['view'](self.ctx, token) return super(SelectBotView, self).get_subview(token) def activate(self): self.links = {} self.views = {} for bot in self.ctx.db.bots.find({'chat_id': self.ctx.chat_id}): self.links['@' + bot['username']] = [self.bot_view['link'], bot['token']] self.links['Назад'] = ['main_view'] super(SelectBotView, self).activate() class OrdersView(NavigationView): def __init__(self, ctx, bot_token): self.ctx = ctx self.token = bot_token self.editable = True self.msg = 'Выберите статус заказа' self.links = { 'В обработке': ['orders_view', self.token, 'in_processing'], 'Завершенные': ['orders_view', self.token, 'done'], "Назад": ['orders_view'] } self.message_id = None self.views = { 'in_processing': AdminOrderView(self.ctx, self.token, status=u'В обработке'), 'done': AdminOrderView(self.ctx, self.token, status=u'Завершен') } class SettingsView(NavigationView): def __init__(self, ctx, bot_token): self.ctx = ctx self.token = bot_token self.editable = True self.msg = 'Настройки' self.links = { 'API token': ['settings_view', self.token, 'token_view'], 'E-mail': ['settings_view', self.token, 'email_view'], 'Загрузка товаров': ['settings_view', self.token, 'items_view'], 'Условия доставки': ['settings_view', self.token, 'delivery_info_view'], 'Контакты': ['settings_view', self.token, 'contacts_view'], 'Минимальная сумма заказа': ['settings_view', self.token, 'total_threshold_view'], 'Личный кабинет': ['settings_view', self.token, 'cabinet_view'], 'Назад': ['settings_view'] } self.message_id = None # if self.token not in self.views: bot = self.ctx.db.bots.find_one({'chat_id': self.ctx.chat_id, 'token': self.token}) self.views = { 'token_view': UpdateBotView(self.ctx, self.token, [TokenDetail('shop.token', name='API token', ctx=self.ctx, value=bot['token'])]), 'email_view': UpdateBotView(self.ctx, self.token, [EmailDetail('shop.email', name='email для приема заказов', ctx=self.ctx, value=bot['email'])]), 'items_view': UpdateBotView(self.ctx, self.token, [FileDetail('shop.items', value=bot['items'], name='файл с описанием товаров или url магазина вконтакте и нажмите \'ОК\'', desc='<a href="https://github.com/0-1-0/marketbot/blob/master/sample.xlsx?raw=true">(Пример файла)</a>')]), 'delivery_info_view': UpdateBotView(self.ctx, self.token, [TextDetail('shop.delivery_info', name='текст с условиями доставки', value=bot.get('delivery_info'))]), 'contacts_view': UpdateBotView(self.ctx, self.token, [TextDetail('shop.contacts_info', name='текст с контактами для связи', value=bot.get('contacts_info'))]), 'total_threshold_view': UpdateBotView(self.ctx, self.token, [NumberDetail('shop.total_threshold', name='минимальную сумму заказа', value=bot.get('total_threshold'))]), 'cabinet_view': CabinetView(self.ctx, self.token) } def get_markup(self): return self.mk_markup(sorted([l.decode('utf-8') for l in self.links.keys()])) class CabinetView(NavigationView): def __init__(self, ctx, bot_token): self.ctx = ctx self.token = bot_token self.editable = True self.msg = 'Ссылка действительна в течение часа' self.links = {'Назад': ['settings_view', self.token]} def get_markup(self): markup = types.ReplyKeyboardMarkup() markup.row(self.BTN('Получить ссылку')) markup.row(self.BTN('Назад')) return markup def process_message(self, cmd): if cmd == 'Получить ссылку': first_part = md5.new() second_part = md5.new() first_part.update(str(int(time() / 60 / 60))) second_part.update(self.token + self.token[::-1]) link = WED_ADMIN_DOMAIN + first_part.hexdigest() + second_part.hexdigest() self.ctx.send_message(link) elif cmd == 'Назад': self.ctx.route(['settings_view', self.token]) else: pass class HelpView(NavigationView): def get_msg(self): return "По всем вопросам обращайтесь к @NikolaII :)" class MailingView(NavigationView): def __init__(self, ctx, bot_token): self.ctx = ctx self.token = bot_token self.editable = True self.msg = 'Введите текст, прикрепите фото или стикер рассылки' self.links = {"Назад": ['mailing_view']} def process_message(self, message): if message in self.links: self.ctx.route(self.links[message]) else: for convo in self.ctx.db.convos.find({'bot_token': self.token}): gevent.spawn(apihelper.send_message, self.token, convo['chat_id'], message, reply_markup=None, parse_mode='HTML') def process_file(self, doc): fid = doc.document.file_id file_info = self.ctx.bot.bot.get_file(fid) content = self.ctx.bot.bot.download_file(file_info.file_path) file_format = file_info.file_path.split('.')[-1] if file_format in ['gif', 'mp4']: for convo in self.ctx.db.convos.find({'bot_token': self.token}): doc = BytesIO(content) doc.name = fid + '.' + file_format gevent.spawn(apihelper.send_data, self.token, convo['chat_id'], doc, 'document', reply_markup=None) else: pass def process_photo(self, photo): caption = photo.caption fid = photo.photo[-1].file_id file_info = self.ctx.bot.bot.get_file(fid) content = self.ctx.bot.bot.download_file(file_info.file_path) file_format = file_info.file_path.split('.')[-1] for convo in self.ctx.db.convos.find({'bot_token': self.token}): photo = BytesIO(content) photo.name = fid + '.' + file_format gevent.spawn(apihelper.send_photo, self.token, convo['chat_id'], photo, caption=caption, reply_markup=None) def process_sticker(self, sticker): fid = sticker.sticker.file_id file_info = self.ctx.bot.bot.get_file(fid) content = self.ctx.bot.bot.download_file(file_info.file_path) file_format = file_info.file_path.split('.')[-1] for convo in self.ctx.db.convos.find({'bot_token': self.token}): doc = BytesIO(content) doc.name = fid + '.' + file_format gevent.spawn(apihelper.send_data, self.token, convo['chat_id'], doc, 'sticker', reply_markup=None) def process_video(self, video): caption = video.caption duration = video.video.duration fid = video.video.file_id file_info = self.ctx.bot.bot.get_file(fid) content = self.ctx.bot.bot.download_file(file_info.file_path) file_format = file_info.file_path.split('.')[-1] for convo in self.ctx.db.convos.find({'bot_token': self.token}): video = BytesIO(content) video.name = fid + '.' + file_format gevent.spawn(apihelper.send_video, self.token, convo['chat_id'], video, caption=caption, duration=duration, reply_markup=None) class Detail(object): def __init__(self, _id, default_options=[], name='', desc='', value=None, ctx=None): self._id = _id self.default_options = default_options self.name = name self.desc = desc self.value = value self.ctx = ctx def is_filled(self): return self.value is not None def validate(self, value): return True def txt(self): return str(self.value) class TextDetail(Detail): pass class NumberDetail(Detail): def validate(self, value): try: int(value) return True except ValueError: return False class TokenDetail(TextDetail): def validate(self, value): if self.ctx.db.bots.find_one({'token': value}) is not None: return False try: b = telebot.TeleBot(value) b.get_me() except: return False return True class EmailDetail(TextDetail): def validate(self, value): return validate_email(value) class FileDetail(Detail): def validate(self, value): return value is not None def txt(self): if self.value: return 'Заполнено' else: return 'Не заполнено'
# -*- coding: utf-8 -*- import sendgrid import os from sendgrid.helpers.mail import * import re import requests import json WED_ADMIN_DOMAIN = open('domain').read().split('\n')[0] def get_address(lat, lng): resp = requests.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + str(lat) + ',' + str(lng) + '&language=ru') return json.loads(resp.content).get('results')[0].get('formatted_address') class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class Mailer(Singleton): sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) def send(self, mail, subj, txt): from_email = Email("order@botmarket.com") subject = subj to_email = Email(mail) content = Content("text/plain", txt) mail = Mail(from_email, subject, to_email, content) return self.sg.client.mail.send.post(request_body=mail.get()) def send_order(self, mail, order): res = 'Заказ\n====\n\n\n' res += '\n'.join(i['name'].encode('utf-8') + ' x ' + str(i['count']) for i in order['items']) res += '\n-----\n Итого: ' + str(order['total']) + ' руб.' res += '\n-----\n Детали доставки: \n' try: res += '\n\n'.join(k.encode('utf-8') + ': ' + v.encode('utf-8') for k, v in order['delivery'].items()) except: res += '\n\n'.join(k + ': ' + v for k, v in order['delivery'].items()) res = res.replace('Ваш', '') return self.send(mail, 'Новый заказ!', res) def striphtml(data): p = re.compile(r'<[brai].*?>|<\/[a].*?>|<span.*?>|<\/span.*?>') res = p.sub('\n', data) return res.replace('&nbsp;', ' ').replace('&mdash;', '-') --- FILE SEPARATOR --- from datetime import datetime from grab.spider import Spider, Task import json import logging import re from selenium import webdriver # data = {} class Crawler(Spider): def __init__(self, url): self.initial_urls = [url] self.data = [] self.d = webdriver.PhantomJS() super(Crawler, self).__init__() def task_initial(self, grab, task): shop_offset = 0 print("Try to parse: " + task.url) shop_url_selector = grab.doc.select('//*[@id="ui_market_items_load_more"]').attr('onclick') re_shop_url = re.compile('market-(\d{1,12})+') shop_url = re_shop_url.search(shop_url_selector).group(0) # 'market-NNNNNN' shop_number = re_shop_url.search(shop_url_selector).group(1) # 'NNNNNN' shop_full_url = ("https://vk.com/" + shop_url) print(shop_url) shop_itemscount = grab.doc.select('//*[@class="module clear market_module _module"]//*[@class="header_count fl_l"]').text() while shop_offset < int(shop_itemscount): yield Task('showcase', url=shop_full_url + '?offset=' + str(shop_offset), shop_key=shop_url, shop_num=shop_number, offset=shop_offset) shop_offset += 24 def task_showcase(self, grab, task): print("Go: " + task.url) re_price = re.compile('>(\d+)\D(\d*)') item_id = 0 + task.offset for item_node in grab.doc.select('//div[@class="market_list"]/div'): item_id += 1 item_attributes = {} item_native_id = item_node.attr('data-id') item_img = item_node.select('div/div/a/img').attr('src') item_price_raw = item_node.select('*/div[@class="market_row_price"]').html() item_price = int(re_price.search(item_price_raw).group(1)) item_price_2 = re_price.search(item_price_raw).group(2) if item_price_2: # remove digit delimiter if price > 1000 (dumb, but working) item_price = item_price * 1000 + int(item_price_2) item_attributes = {"id": item_id, "native_id": item_native_id, "img": item_img, "price": item_price, "name": "", "cat": ""} self.item_details(item_attributes=item_attributes, shop=task.shop_num, item_native_id=item_native_id, item_key=item_id) def item_details(self, item_attributes, shop, item_native_id, item_key): d = self.d url = 'http://vk.com/market-' + str(shop) + '?w=product-' + str(shop) + '_' + str(item_native_id) d.get(url) d.implicitly_wait(.9) item_desc = d.find_element_by_id("market_item_description").text item_cat = d.find_element_by_class_name("market_item_category").text item_attributes['desc'] = item_desc item_attributes['name'] = item_desc.split('.')[0][:80] # TODO hack item_attributes['cat'] = item_cat self.data.append(item_attributes) def fetch(self): self.run() return self.data # def export_file(data,filename): # filename = filename # with open(filename, 'w') as f: # json.dump(data, f) # return json.dumps(data) def main(): print Crawler('https://vk.com/spark.design').fetch() if __name__ == '__main__': main()
{ "imports": [ "/utils.py", "/vk_crawler.py" ] }
0-1-0/marketbot
refs/heads/master
/polling_listener.py
from gevent import monkey; monkey.patch_all() from utils import Singleton import telebot import copy import json from app import MasterBot, Bot class PollingProcessor(Singleton): tokens = {} mb = MasterBot({'token': open('token').read().replace('\n', '')}) def get_updates(self, silent=False): res = False for token in copy.copy(Bot.bots.keys()): updates = telebot.apihelper.get_updates(token, offset=self.tokens.get(token) or 0) for update in updates: if update['update_id'] > self.tokens.get(token): self.tokens[token] = update['update_id'] res = True if not silent: self.mb.route_update(token, json.dumps(update)) return res def start(self): while self.get_updates(silent=True): pass while True: self.get_updates() if __name__ == "__main__": PollingProcessor().start()
# -*- coding: utf-8 -*- import sendgrid import os from sendgrid.helpers.mail import * import re import requests import json WED_ADMIN_DOMAIN = open('domain').read().split('\n')[0] def get_address(lat, lng): resp = requests.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + str(lat) + ',' + str(lng) + '&language=ru') return json.loads(resp.content).get('results')[0].get('formatted_address') class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class Mailer(Singleton): sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) def send(self, mail, subj, txt): from_email = Email("order@botmarket.com") subject = subj to_email = Email(mail) content = Content("text/plain", txt) mail = Mail(from_email, subject, to_email, content) return self.sg.client.mail.send.post(request_body=mail.get()) def send_order(self, mail, order): res = 'Заказ\n====\n\n\n' res += '\n'.join(i['name'].encode('utf-8') + ' x ' + str(i['count']) for i in order['items']) res += '\n-----\n Итого: ' + str(order['total']) + ' руб.' res += '\n-----\n Детали доставки: \n' try: res += '\n\n'.join(k.encode('utf-8') + ': ' + v.encode('utf-8') for k, v in order['delivery'].items()) except: res += '\n\n'.join(k + ': ' + v for k, v in order['delivery'].items()) res = res.replace('Ваш', '') return self.send(mail, 'Новый заказ!', res) def striphtml(data): p = re.compile(r'<[brai].*?>|<\/[a].*?>|<span.*?>|<\/span.*?>') res = p.sub('\n', data) return res.replace('&nbsp;', ' ').replace('&mdash;', '-') --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import gevent from gevent import monkey; monkey.patch_all() import telebot from telebot import apihelper from pymongo import MongoClient from views import * from utils import get_address import botan import time botan_token = 'BLe0W1GY8SwbNijJ0H-lroERrA9BnK0t' class Convo(object): def __init__(self, data, bot): self.bot = bot self.token = bot.token self.db = bot.db self.chat_id = data['chat_id'] self.views = {} self.path = data.get('path') self.tmpdata = None def get_current_view(self): if self.path and self.path[0] in self.views: return self.views[self.path[0]].route(self.path[1:]) return None def get_bot_data(self): return self.db.bots.find_one({'token': self.token}) def _send_msg(self, msg1, markup): try: apihelper.send_message(self.token, self.chat_id, msg1, reply_markup=markup, parse_mode='HTML') except Exception, e: self.bot.log_error({'func': '_send_msg', 'token': self.token, 'chat_id': self.chat_id, 'message': msg1, 'error': str(e)}) def send_message(self, msg, markup=None): if self.chat_id: msg1 = msg.replace('<br />', '.\n') gevent.spawn(self._send_msg, msg1, markup) return def edit_message(self, message_id, msg, markup=None): if self.chat_id: msg1 = msg.replace('<br />', '.\n') gevent.spawn(apihelper.edit_message_text, self.token, msg1, self.chat_id, message_id=message_id, reply_markup=markup, parse_mode='HTML') return def process_message(self, message): try: txt = message.text.encode('utf-8') except: if hasattr(message, 'contact') and message.contact is not None: txt = message.contact.phone_number if hasattr(message, 'location') and message.location is not None: txt = get_address(message.location.latitude, message.location.longitude).encode('utf-8') if txt: self.send_message(txt) self.get_current_view().process_message(txt) def process_photo(self, photo): self.get_current_view().process_photo(photo) def process_sticker(self, sticker): self.get_current_view().process_sticker(sticker) def process_video(self, video): self.get_current_view().process_video(video) def process_callback(self, callback): self.get_current_view().process_callback(callback) def process_file(self, doc): self.get_current_view().process_file(doc) def set_path(self, path): self.path = path gevent.spawn(self.db.convos.update_one, {'bot_token': self.bot.token, 'chat_id': self.chat_id}, {'$set': {'path': path}}) def route(self, path): self.set_path(path) self.get_current_view().activate() class MarketBotConvo(Convo): def __init__(self, data, bot): super(MarketBotConvo, self).__init__(data, bot) self.current_basket = None self.views['delivery'] = OrderCreatorView(self, [], final_message='Заказ сформирован!') self.views['menu_cat_view'] = MenuCatView(self, msg="Выберите категорию:") self.views['order_info'] = OrderInfoView(self, msg="Тут должны быть условия доставки", links={'Главное меню': ['main_view']}) self.views['contacts'] = ContactsInfoView(self, links={'Главное меню': ['main_view']}) self.views['history'] = HistoryView(self) self.views['main_view'] = NavigationView(self, links={ "Меню": ['menu_cat_view'], "История": ['history'], "Доставка": ['order_info'], # , "Контакты": ['contacts'] # ContactsInfoView(self.ctx) }, msg="Главное меню") self.path = data.get('path') if not self.get_current_view(): self.route(['main_view']) class MainConvo(Convo): def __init__(self, data, bot): super(MainConvo, self).__init__(data, bot) self.views['main_view'] = NavigationView( self, links={ "Добавить магазин": ['add_view'], "Настройки": ['settings_view'], "Заказы": ['orders_view'], "Помощь": ['help_view'], "Рассылка новостей": ['mailing_view'] }, msg="Главное меню" ) self.views['help_view'] = HelpView(self, links={'Назад': ['main_view']}) self.views['add_view'] = BotCreatorView(self, [ TokenDetail('shop.token', name='API token.', desc='Для этого перейдите в @BotFather и нажмите /newbot для создания бота. Придумайте название бота (должно быть на русском языке) и ссылку на бот (на английском языке и заканчиваться на bot). Далее вы увидите API token, который нужно скопировать и отправить в этот чат.', ctx=self), EmailDetail('shop.email', name='email для приема заказов', ctx=self), FileDetail('shop.items', name='файл с описанием товаров или url магазина вконтакте', desc='<a href="https://github.com/0-1-0/marketbot/blob/master/sample.xlsx?raw=true">Пример файла</a>'), TextDetail('shop.delivery_info', name='текст с условиями доставки'), TextDetail('shop.contacts_info', name='текст с контактами для связи', value='telegram: @' + str(self.bot.bot.get_chat(self.chat_id).username)), NumberDetail('shop.total_threshold', name='минимальную сумму заказа', value='0') ], final_message='Магазин создан!') self.views['settings_view'] = SelectBotView(self, bot_view={'link': 'settings_view', 'view': SettingsView}) self.views['orders_view'] = SelectBotView(self, bot_view={'link': 'orders_view', 'view': OrdersView}) self.views['mailing_view'] = SelectBotView(self, bot_view={'link': 'mailing_view', 'view': MailingView}) self.path = data.get('path') if not self.get_current_view(): self.route(['main_view']) class Bot(object): bots = {} WEBHOOK_HOST = 'ec2-52-34-35-240.us-west-2.compute.amazonaws.com' WEBHOOK_PORT = 8443 WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT) WEBHOOK_SSL_CERT = '/home/ubuntu/webhook_cert.pem' def __init__(self, token): self.token = token Bot.bots[self.token] = self gevent.spawn(self.set_webhook, self.token) def log_error(self, e): pass def set_webhook(self, token, retries=0): try: bot = telebot.TeleBot(token) bot.remove_webhook() bot.set_webhook(url=self.WEBHOOK_URL_BASE + '/' + bot.token + '/', certificate=open(self.WEBHOOK_SSL_CERT, 'r')) print token, 'registered' except Exception, e: self.log_error(e) print token, e if retries < 2: time.sleep(1) self.set_webhook(token, retries+1) class MarketBot(Bot): convo_type = MarketBotConvo def __init__(self, data, db=MongoClient()['marketbot']): super(MarketBot, self).__init__(data['token']) self.convos = {} self.db = db if not self.db.bots.update_one({'token': self.token}, {'$set': apihelper.get_me(self.token)}): self.db.bots.insert_one({'token': self.token}) self.email = data.get('email') self.last_update_id = data.get('last_update_id') or 0 self._init_bot() for convo_data in self.db.convos.find({'bot_token': self.token}): self.init_convo(convo_data) def log_error(self, e): gevent.spawn(self.db.errors.insert_one, {'error': str(e)}) def _init_bot(self, threaded=False): self.bot = telebot.TeleBot(self.token, threaded=threaded, skip_pending=True) self.bot.add_message_handler(self.goto_main, commands=['start']) self.bot.add_callback_query_handler(self.process_callback, func=lambda call: True) self.bot.add_message_handler(self.process_photo, content_types=['photo']) self.bot.add_message_handler(self.process_video, content_types=['video']) self.bot.add_message_handler(self.process_sticker, content_types=['sticker']) self.bot.add_message_handler(self.process_file, content_types=['document']) self.bot.add_message_handler(self.process_message, func=lambda message: True, content_types=['text', 'contact', 'location']) def init_convo(self, convo_data): self.convos[convo_data['chat_id']] = self.convo_type(convo_data, self) def get_convo(self, chat_id): if chat_id not in self.convos: convo_data = {'chat_id': chat_id, 'bot_token': self.token} self.db.convos.insert_one(convo_data) self.init_convo(convo_data) return self.convos[chat_id] def goto_main(self, message): convo = self.get_convo(message.chat.id) convo.route(['main_view']) def process_callback(self, callback): convo = self.get_convo(callback.message.chat.id) gevent.spawn(convo.process_callback, callback) def process_message(self, message): convo = self.get_convo(message.chat.id) gevent.spawn(convo.process_message, message) def start_bot(self, bot_data): MarketBot(bot_data, self.db) def process_file(self, doc): convo = self.get_convo(doc.chat.id) convo.process_file(doc) def process_sticker(self, sticker): convo = self.get_convo(sticker.chat.id) convo.process_sticker(sticker) def process_video(self, video): convo = self.get_convo(video.chat.id) convo.process_video(video) def process_photo(self, photo): convo = self.get_convo(photo.chat.id) gevent.spawn(convo.process_photo, photo) def update_last_id(self): self.db.bots.update_one({'token': self.token}, {'$set': {'last_update_id': self.last_update_id}}) def process_redis_update(self, update): if isinstance(update, basestring): update = telebot.types.Update.de_json(update.encode('utf-8')) if update.update_id > self.last_update_id: self.last_update_id = update.update_id gevent.spawn(self.bot.process_new_updates, [update]) gevent.spawn(self.update_last_id) class MasterBot(MarketBot): convo_type = MainConvo def process_message(self, message): gevent.spawn(botan.track, botan_token, message.chat.id, {'from_user': message.from_user.username}, message.text) super(MasterBot, self).process_message(message) def __init__(self, data): super(MasterBot, self).__init__(data) for bot_data in self.db.bots.find(): if bot_data['token'] != self.token: try: MarketBot(bot_data, self.db) except Exception, e: self.log_error(e) def route_update(self, token, update): if token in Bot.bots: gevent.spawn(Bot.bots[token].process_redis_update, update) return if __name__ == "__main__": m = MasterBot({'token': open('token').read().replace('\n', '')}) gevent.spawn(m.run).join()
{ "imports": [ "/utils.py", "/app.py" ] }
00-a/Staff
refs/heads/master
/staff/serializers.py
from rest_framework import serializers from .models import Employee class RecursiveSerializer(serializers.Serializer): """Recursive for employee children""" def to_representation(self, data): serializer = self.parent.parent.__class__(data, context=self.context) return serializer.data class StaffListSerializer(serializers.ModelSerializer): """List of staff""" position = serializers.SlugRelatedField(slug_field="name", read_only=True) children = RecursiveSerializer(many=True) class Meta: model = Employee fields = '__all__' class ChildrenEmployeeDetailSerializer(serializers.ModelSerializer): """Serializer for employee children in detail view""" class Meta: model = Employee fields = ('name', 'surname') class EmployeeDetailSerializer(serializers.ModelSerializer): """Details of employee""" position = serializers.SlugRelatedField(slug_field="name", read_only=True) parent = serializers.SlugRelatedField(slug_field="name", read_only=True) children = ChildrenEmployeeDetailSerializer(many=True) class Meta: model = Employee fields = '__all__' class EmployeeCreateSerializer(serializers.ModelSerializer): """Create a new employee""" class Meta: model = Employee fields = '__all__'
from django.db import models class Employee(models.Model): """Employee. Parent - employee chief""" name = models.CharField(max_length=50) surname = models.CharField(max_length=50) position = models.ForeignKey('Position', on_delete=models.SET_NULL, null=True) salary = models.PositiveIntegerField(default=0) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children', verbose_name='Chief') photo = models.ImageField(upload_to='staffphotos/', blank=True) employment_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} {self.surname}' class Meta: verbose_name = 'Employee' verbose_name_plural = 'Staff' class Position(models.Model): """Employee position""" name = models.CharField(max_length=100, verbose_name='Position name') def __str__(self): return self.name
{ "imports": [ "/staff/models.py" ] }
00-a/Staff
refs/heads/master
/staff/urls.py
from django.urls import path from .views import StaffListView, EmployeeDetailView, EmployeeCreateView urlpatterns = [ path('staff/', StaffListView.as_view()), path('staff/<int:pk>', EmployeeDetailView.as_view()), path('staff/create', EmployeeCreateView.as_view()) ]
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import IsAuthenticated, IsAdminUser from .models import Employee from .serializers import StaffListSerializer, EmployeeDetailSerializer, EmployeeCreateSerializer from .services import StaffFilter class StaffListView(generics.ListAPIView): """List of staff""" serializer_class = StaffListSerializer filter_backends = (DjangoFilterBackend,) filterset_class = StaffFilter pagination_class = PageNumberPagination permission_classes = [IsAdminUser] queryset = Employee.objects.filter(parent=None) class EmployeeDetailView(generics.RetrieveAPIView): """Employee detail""" queryset = Employee.objects.all() permission_classes = [IsAuthenticated] serializer_class = EmployeeDetailSerializer class EmployeeCreateView(generics.CreateAPIView): """Create a new employee""" permission_classes = [IsAuthenticated] serializer_class = EmployeeCreateSerializer
{ "imports": [ "/staff/views.py" ] }
00-a/Staff
refs/heads/master
/staff/views.py
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import IsAuthenticated, IsAdminUser from .models import Employee from .serializers import StaffListSerializer, EmployeeDetailSerializer, EmployeeCreateSerializer from .services import StaffFilter class StaffListView(generics.ListAPIView): """List of staff""" serializer_class = StaffListSerializer filter_backends = (DjangoFilterBackend,) filterset_class = StaffFilter pagination_class = PageNumberPagination permission_classes = [IsAdminUser] queryset = Employee.objects.filter(parent=None) class EmployeeDetailView(generics.RetrieveAPIView): """Employee detail""" queryset = Employee.objects.all() permission_classes = [IsAuthenticated] serializer_class = EmployeeDetailSerializer class EmployeeCreateView(generics.CreateAPIView): """Create a new employee""" permission_classes = [IsAuthenticated] serializer_class = EmployeeCreateSerializer
from django.db import models class Employee(models.Model): """Employee. Parent - employee chief""" name = models.CharField(max_length=50) surname = models.CharField(max_length=50) position = models.ForeignKey('Position', on_delete=models.SET_NULL, null=True) salary = models.PositiveIntegerField(default=0) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children', verbose_name='Chief') photo = models.ImageField(upload_to='staffphotos/', blank=True) employment_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} {self.surname}' class Meta: verbose_name = 'Employee' verbose_name_plural = 'Staff' class Position(models.Model): """Employee position""" name = models.CharField(max_length=100, verbose_name='Position name') def __str__(self): return self.name --- FILE SEPARATOR --- from rest_framework import serializers from .models import Employee class RecursiveSerializer(serializers.Serializer): """Recursive for employee children""" def to_representation(self, data): serializer = self.parent.parent.__class__(data, context=self.context) return serializer.data class StaffListSerializer(serializers.ModelSerializer): """List of staff""" position = serializers.SlugRelatedField(slug_field="name", read_only=True) children = RecursiveSerializer(many=True) class Meta: model = Employee fields = '__all__' class ChildrenEmployeeDetailSerializer(serializers.ModelSerializer): """Serializer for employee children in detail view""" class Meta: model = Employee fields = ('name', 'surname') class EmployeeDetailSerializer(serializers.ModelSerializer): """Details of employee""" position = serializers.SlugRelatedField(slug_field="name", read_only=True) parent = serializers.SlugRelatedField(slug_field="name", read_only=True) children = ChildrenEmployeeDetailSerializer(many=True) class Meta: model = Employee fields = '__all__' class EmployeeCreateSerializer(serializers.ModelSerializer): """Create a new employee""" class Meta: model = Employee fields = '__all__' --- FILE SEPARATOR --- from django_filters import rest_framework as filters from staff.models import Employee class StaffFilter(filters.FilterSet): salary = filters.RangeFilter() employment_date = filters.RangeFilter() class Meta: model = Employee fields = ('position', 'salary', 'employment_date')
{ "imports": [ "/staff/models.py", "/staff/serializers.py", "/staff/services.py" ] }
00-a/Staff
refs/heads/master
/staff/services.py
from django_filters import rest_framework as filters from staff.models import Employee class StaffFilter(filters.FilterSet): salary = filters.RangeFilter() employment_date = filters.RangeFilter() class Meta: model = Employee fields = ('position', 'salary', 'employment_date')
from django.db import models class Employee(models.Model): """Employee. Parent - employee chief""" name = models.CharField(max_length=50) surname = models.CharField(max_length=50) position = models.ForeignKey('Position', on_delete=models.SET_NULL, null=True) salary = models.PositiveIntegerField(default=0) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children', verbose_name='Chief') photo = models.ImageField(upload_to='staffphotos/', blank=True) employment_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} {self.surname}' class Meta: verbose_name = 'Employee' verbose_name_plural = 'Staff' class Position(models.Model): """Employee position""" name = models.CharField(max_length=100, verbose_name='Position name') def __str__(self): return self.name
{ "imports": [ "/staff/models.py" ] }
0000duck/hpp_source_code
refs/heads/master
/install/lib/python2.7/dist-packages/hpp/corbaserver/manipulation/__init__.py
import hpp_idl.hpp.manipulation_idl from .client import Client from .problem_solver import ProblemSolver, newProblem from .constraint_graph import ConstraintGraph from .constraint_graph_factory import ConstraintGraphFactory from .constraints import Constraints from .robot import CorbaClient, Robot from hpp.corbaserver import loadServerPlugin, createContext from hpp_idl.hpp.corbaserver.manipulation import Rule
#!/usr/bin/env python # # Copyright (c) 2014 CNRS # Author: Florent Lamiraux # # This file is part of hpp-manipulation-corba. # hpp-manipulation-corba is free software: you can redistribute it # and/or modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either version # 3 of the License, or (at your option) any later version. # # hpp-manipulation-corba is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Lesser Public License for more details. You should have # received a copy of the GNU Lesser General Public License along with # hpp-manipulation-corba. If not, see # <http://www.gnu.org/licenses/>. from hpp.corbaserver.client import Client as _Parent from hpp_idl.hpp.corbaserver.manipulation import Graph, Robot, Problem class Client (_Parent): """ Connect and create clients for hpp-manipulation library. """ defaultClients = { 'graph' : Graph, 'problem': Problem, 'robot' : Robot, } def __init__(self, url = None, context = "corbaserver"): """ Initialize CORBA and create default clients. :param url: URL in the IOR, corbaloc, corbalocs, and corbanames formats. For a remote corba server, use url = "corbaloc:iiop:<host>:<port>/NameService" """ self._initOrb (url) self._makeClients ("manipulation", self.defaultClients, context) --- FILE SEPARATOR --- #!/usr/bin/env python # # Copyright (c) 2014 CNRS # Author: Florent Lamiraux # # This file is part of hpp-manipulation-corba. # hpp-manipulation-corba is free software: you can redistribute it # and/or modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either version # 3 of the License, or (at your option) any later version. # # hpp-manipulation-corba is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Lesser Public License for more details. You should have # received a copy of the GNU Lesser General Public License along with # hpp-manipulation-corba. If not, see # <http://www.gnu.org/licenses/>. def newProblem (client = None, name = None): from hpp.corbaserver.problem_solver import newProblem if client is None: from hpp.corbaserver.manipulation import Client client = Client() newProblem (client = client, name = name) from hpp.corbaserver.problem_solver import _convertToCorbaAny, ProblemSolver as Parent ## Definition of a manipulation planning problem # # This class wraps the Corba client to the server implemented by # libhpp-manipulation-corba.so # # Some method implemented by the server can be considered as private. The # goal of this class is to hide them and to expose those that can be # considered as public. class ProblemSolver (Parent): def __init__ (self, robot): super (ProblemSolver, self).__init__ (robot, hppcorbaClient = robot.client.basic) ## Select a problem by its name. # If no problem with this name exists, a new # hpp::manipulation::ProblemSolver is created and selected. # \param name the problem name. # \return true if a new problem was created. def selectProblem (self, name): return self.client.manipulation.problem.selectProblem (name) ## Return a list of available elements of type type # \param type enter "type" to know what types I know of. # This is case insensitive. def getAvailable (self, type): if type.lower () == "type": res = self.client.basic.problem.getAvailable (type) + \ self.client.manipulation.problem.getAvailable (type) return res try: return self.client.basic.problem.getAvailable (type) except: return self.client.manipulation.problem.getAvailable (type) ## Return a list of selected elements of type type # \param type enter "type" to know what types I know of. # This is case insensitive. # \note For most of the types, the list will contain only one element. def getSelected (self, type): try: return self.client.basic.problem.getSelected (type) except: return self.client.manipulation.problem.getSelected (type) ## \name Constraints # \{ ## Create placement and pre-placement constraints # # \param width set to None to skip creation of pre-placement constraint # # See hpp::corbaserver::manipulation::Problem::createPlacementConstraint # and hpp::corbaserver::manipulation::Problem::createPrePlacementConstraint def createPlacementConstraints (self, placementName, shapeName, envContactName, width = 0.05): name = placementName self.client.manipulation.problem.createPlacementConstraint (name, shapeName, envContactName) if width is not None: prename = "pre_" + name self.client.manipulation.problem.createPrePlacementConstraint (prename, shapeName, envContactName, width) return name, prename return name ## Return balance constraints created by method # ProblemSolver.createStaticStabilityConstraints def balanceConstraints (self): return self.balanceConstraints_ ## Get whether right hand side of a numerical constraint is constant # \param constraintName Name of the numerical constraint, # \return whether right hand side is constant # \note LockedJoint have non constant right hand side def getConstantRightHandSide (self, constraintName) : if constraintName in self.getAvailable ('LockedJoint'): return False return self.client.basic.problem.getConstantRightHandSide \ (constraintName) ## Lock degree of freedom of a FreeFlyer joint # \param freeflyerBname base name of the joint # (It will be completed by '_xyz' and '_SO3'), # \param lockJointBname base name of the LockedJoint constraints # (It will be completed by '_xyz' and '_SO3'), # \param values config of the locked joints (7 float) def lockFreeFlyerJoint (self, freeflyerBname, lockJointBname, values = (0,0,0,0,0,0,1)): lockedJoints = list () self.createLockedJoint (lockJointBname, freeflyerBname, values) lockedJoints.append (lockJointBname) return lockedJoints ## Lock degree of freedom of a planar joint # \param jointName name of the joint # (It will be completed by '_xy' and '_rz'), # \param lockJointName name of the LockedJoint constraint # \param values config of the locked joints (4 float) def lockPlanarJoint (self, jointName, lockJointName, values = (0,0,1,0)): lockedJoints = list () self.createLockedJoint (lockJointName, jointName, values) lockedJoints.append (lockJointName) return lockedJoints ## \} ## \name Solve problem and get paths # \{ ## Set the problem target to stateId # The planner will look for a path from the init configuration to a configuration in # state stateId def setTargetState (self, stateId): self.client.manipulation.problem.setTargetState(stateId) ## \} --- FILE SEPARATOR --- #!/usr/bin/env python # # Copyright (c) 2017 CNRS # Author: Joseph Mirabel # # This file is part of hpp-manipulation-corba. # hpp-manipulation-corba is free software: you can redistribute it # and/or modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either version # 3 of the License, or (at your option) any later version. # # hpp-manipulation-corba is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Lesser Public License for more details. You should have # received a copy of the GNU Lesser General Public License along with # hpp-manipulation-corba. If not, see # <http://www.gnu.org/licenses/>. import re, abc, sys from .constraints import Constraints def _removeEmptyConstraints (problem, constraints): return [ n for n in constraints if problem.getConstraintDimensions(n)[2] > 0 ] class Rules(object): def __init__ (self, grippers, handles, rules): rs = [] status = [] for r in rules: # replace empty strings by the corresponding regexp "^$", otherwise "" matches with all strings. for i in range(len(r.grippers)): if r.grippers[i] == "": r.grippers[i] = "^$" for i in range(len(r.handles)): if r.handles[i] == "": r.handles[i] = "^$" handlesRegex = [ None ] * len(grippers) for j, gr in enumerate (r.grippers): grc = re.compile (gr) for i, g in enumerate (grippers): if grc.match (g): assert handlesRegex[i] is None handlesRegex[i] = re.compile(r.handles[j]) status.append(r.link) rs.append (tuple(handlesRegex)) self.rules = tuple(rs) self.status = tuple(status) self.handles = tuple(handles) self.defaultAcceptation = False def __call__ (self, grasps): for r, s in zip(self.rules, self.status): apply = True for i, h in enumerate(r): if h is not None and not h.match("" if grasps[i] is None else self.handles[grasps[i]]): # This rule does not apply apply = False break if apply: return s return self.defaultAcceptation if sys.version_info.major == 2: class ABC: """ Python 2.7 equivalent to abc.ABC Python 3 class.""" __metaclass__ = abc.ABCMeta else: from abc import ABC ## An abstract class which is loops over the different (gripper, handle) associations. # # The behaviour can be tuned by setting the callback functions: # - \ref graspIsAllowed (redundant with \ref setRules) # - \ref constraint_graph_factory_algo_callbacks "Algorithm steps" class GraphFactoryAbstract(ABC): def __init__(self): ## Reduces the problem combinatorial. # Function called to check whether a grasps is allowed. # It takes as input a list of handle indices (or None) such # that i-th \ref grippers grasps `grasps[i]`-th \ref handles. # It must return a boolean # # It defaults to: \code lambda x : True self.graspIsAllowed = lambda x : True ## \name Internal variables # \{ self.states = dict() self.transitions = set() ## the handle names self.handles = tuple() # strings ## the gripper names self.grippers = tuple() # strings ## the names of contact on the environment self.envContacts = tuple () # strings ## the object names self.objects = tuple () # strings ## See \ref setObjects self.handlesPerObjects = tuple () # object index to handle indixes ## See \ref setObjects self.objectFromHandle = tuple () # handle index to object index ## See \ref setObjects self.contactsPerObjects = tuple ()# object index to contact names ## \} ## \name Main API # \{ ## \param grippers list of gripper names to be considered def setGrippers(self, grippers): assert isinstance (grippers, (list, tuple)) self.grippers = tuple(grippers) ## \param objects list of object names to be considered ## \param handlesPerObjects a list of list of handle names. ## \param contactsPerObjects a list of list of contact names. ## handlesPerObjects and contactsPerObjects must have one list for each object, in the same order. def setObjects(self, objects, handlesPerObjects, contactsPerObjects): self.objects = tuple(objects) handles = [] hpo = [] cpo = [] ofh = [] for io, o in enumerate (self.objects): hpo.append( tuple(range(len(handles), len(handles) + len(handlesPerObjects[io])) ) ) handles.extend(handlesPerObjects[io]) ofh.extend( [ io, ] * len(handlesPerObjects[io]) ) cpo.append( tuple(contactsPerObjects[io]) ) self.handles = tuple(handles) self.handlesPerObjects = tuple(hpo) self.objectFromHandle = tuple(ofh) self.contactsPerObjects = tuple(cpo) ## \param envContacts contact on the environment to be considered. def environmentContacts (self, envContacts): self.envContacts = tuple(envContacts) ## Set the function \ref graspIsAllowed ## \param rules a list of Rule objects def setRules (self, rules): self.graspIsAllowed = Rules(self.grippers, self.handles, rules) ## Go through the combinatorial defined by the grippers and handles # and create the states and transitions. def generate(self): grasps = ( None, ) * len(self.grippers) self._recurse(self.grippers, self.handles, grasps, 0) ## \} ## \name Abstract methods of the algorithm # \anchor constraint_graph_factory_algo_callbacks # \{ ## Create a new state. # \param grasps a handle index for each gripper, as in GraphFactoryAbstract.graspIsAllowed. # \param priority the state priority. # \return an object representing the state. @abc.abstractmethod def makeState(self, grasps, priority): return grasps ## Create a loop transition. # \param state: an object returned by \ref makeState which represent the state @abc.abstractmethod def makeLoopTransition(self, state): pass ## Create two transitions between two different states. # \param stateFrom: same as grasps in \ref makeState # \param stateTo: same as grasps in \ref makeState # \param ig: index if the grasp vector that changes, i.e. such that # - \f$ stateFrom.grasps[i_g] \neq stateTo.grasps[i_g] \f$ # - \f$ \forall i \neq i_g, stateFrom.grasps[i] = stateTo.grasps[i] \f$ @abc.abstractmethod def makeTransition(self, stateFrom, stateTo, ig): pass ## \} def _makeState(self, grasps, priority): if grasps not in self.states: state = self.makeState (grasps, priority) self.states[grasps] = state # Create loop transition self.makeLoopTransition (state) else: state = self.states [grasps] return state def _isObjectGrasped(self, grasps, object): for h in self.handlesPerObjects[object]: if h in grasps: return True return False def _stateName (self, grasps, abbrev = False): sepGH = "-" if abbrev else " grasps " sep = ":" if abbrev else " : " name = sep.join([ (str(ig) if abbrev else self.grippers[ig]) + sepGH + (str(ih) if abbrev else self.handles[ih]) for ig,ih in enumerate(grasps) if ih is not None ]) if len(name) == 0: return "f" if abbrev else "free" return name def _transitionNames (self, sFrom, sTo, ig): g = self.grippers[ig] h = self.handles[sTo.grasps[ig]] sep = " | " return (g + " > " + h + sep + self._stateName(sFrom.grasps, True), g + " < " + h + sep + self._stateName(sTo.grasps, True),) def _loopTransitionName (self, grasps): return "Loop | " + self._stateName(grasps, True) def _recurse(self, grippers, handles, grasps, depth): isAllowed = self.graspIsAllowed (grasps) if isAllowed: current = self._makeState (grasps, depth) if len(grippers) == 0 or len(handles) == 0: return for ig, g in enumerate(grippers): ngrippers = grippers[:ig] + grippers[ig+1:] isg = self.grippers.index(g) for ih, h in enumerate(handles): nhandles = handles[:ih] + handles[ih+1:] ish = self.handles.index(h) nGrasps = grasps[:isg] + (ish, ) + grasps[isg+1:] nextIsAllowed = self.graspIsAllowed (nGrasps) if nextIsAllowed: next = self._makeState (nGrasps, depth + 1) if isAllowed and nextIsAllowed: self.makeTransition (current, next, isg) self._recurse (ngrippers, nhandles, nGrasps, depth + 2) ## An abstract class which stores the constraints. # # Child classes are responsible for building them. # - \ref buildGrasp # - \ref buildPlacement class ConstraintFactoryAbstract(ABC): def __init__(self, graphfactory): self._grasp = dict() self._placement = dict() self.graphfactory = graphfactory ## \name Accessors to the different elementary constraints # \{ def getGrasp(self, gripper, handle): if isinstance(gripper, str): ig = self.graphfactory.grippers.index(gripper) else: ig = gripper if isinstance(handle, str): ih = self.graphfactory.handles.index(handle) else: ih = handle k = (ig, ih) if k not in self._grasp: self._grasp[k] = self.buildGrasp(self.graphfactory.grippers[ig], None if ih is None else self.graphfactory.handles[ih]) assert isinstance (self._grasp[k], dict) return self._grasp[k] def g (self, gripper, handle, what): return self.getGrasp(gripper, handle)[what] def getPlacement(self, object): if isinstance(object, str): io = self.graphfactory.objects.index(object) else: io = object k = io if k not in self._placement: self._placement[k] = self.buildPlacement(self.graphfactory.objects[io]) return self._placement[k] def p (self, object, what): return self.getPlacement(object)[what] ## \} ## Function called to create grasp constraints. # Must return a tuple of Constraints objects as: # - constraint that validates the grasp # - constraint that parameterizes the graph # - constraint that validates the pre-grasp # \param g gripper string # \param h handle string @abc.abstractmethod def buildGrasp (self, g, h): return (None, None, None,) ## Function called to create placement constraints. # Must return a tuple of Constraints objects as: # - constraint that validates placement # - constraint that parameterizes placement # - constraint that validates pre-placement # \param o string @abc.abstractmethod def buildPlacement (self, o): return (None, None, None,) ## Default implementation of ConstraintFactoryAbstract class ConstraintFactory(ConstraintFactoryAbstract): gfields = ('grasp', 'graspComplement', 'preGrasp') pfields = ('placement', 'placementComplement', 'prePlacement') def __init__ (self, graphfactory, graph): super (ConstraintFactory, self).__init__(graphfactory) self.graph = graph ## Select whether placement should be strict or relaxed. # \sa buildStrictPlacement, buildRelaxedPlacement self.strict = False ## Calls ConstraintGraph.createGraph and ConstraintGraph.createPreGrasp ## \param g gripper string ## \param h handle string def buildGrasp (self, g, h): n = g + " grasps " + h pn = g + " pregrasps " + h self.graph.createGrasp (n, g, h) self.graph.createPreGrasp (pn, g, h) return dict ( list(zip (self.gfields, ( Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n, ])), Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n + "/complement", ])), Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ pn, ])), )))) def buildPlacement (self, o): if self.strict: return self.buildStrictPlacement (o) else: return self.buildRelaxedPlacement (o) ## This implements strict placement manifolds, ## where the parameterization constraints is the complement ## of the placement constraint. ## \param o string def buildStrictPlacement (self, o): n = "place_" + o pn = "preplace_" + o width = 0.05 io = self.graphfactory.objects.index(o) placeAlreadyCreated = n in self.graph.clientBasic.problem.getAvailable ("numericalconstraint") if (len(self.graphfactory.contactsPerObjects[io]) == 0 or len(self.graphfactory.envContacts) == 0) and not placeAlreadyCreated: ljs = [] for n in self.graph.clientBasic.robot.getJointNames(): if n.startswith(o + "/"): ljs.append(n) q = self.graph.clientBasic.robot.getJointConfig(n) self.graph.clientBasic.problem.createLockedJoint(n, n, q) return dict ( list(zip (self.pfields, (Constraints (), Constraints (lockedJoints = ljs), Constraints (),)))) if not placeAlreadyCreated: self.graph.client.problem.createPlacementConstraint (n, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts) if not pn in self.graph.clientBasic.problem.getAvailable ("numericalconstraint"): self.graph.client.problem.createPrePlacementConstraint (pn, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts, width) return dict ( list(zip (self.pfields, ( Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n, ])), Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n + "/complement", ])), Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ pn, ])), )))) ## This implements relaxed placement manifolds, ## where the parameterization constraints is the LockedJoint of ## the object root joint ## \param o string def buildRelaxedPlacement (self, o): n = "place_" + o pn = "preplace_" + o width = 0.05 io = self.graphfactory.objects.index(o) ljs = [] for jn in self.graph.clientBasic.robot.getJointNames(): if jn.startswith(o + "/"): ljs.append(jn) q = self.graph.clientBasic.robot.getJointConfig(jn) self.graph.clientBasic.problem.createLockedJoint(jn, jn, q) placeAlreadyCreated = n in self.graph.clientBasic.problem.getAvailable ("numericalconstraint") if (len(self.graphfactory.contactsPerObjects[io]) == 0 or len(self.graphfactory.envContacts) == 0) and not placeAlreadyCreated: return dict ( list(zip (self.pfields, (Constraints (), Constraints (lockedJoints = ljs), Constraints (),)))) if not placeAlreadyCreated: self.graph.client.problem.createPlacementConstraint (n, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts) if not pn in self.graph.clientBasic.problem.getAvailable ("numericalconstraint"): self.graph.client.problem.createPrePlacementConstraint (pn, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts, width) return dict ( list(zip (self.pfields, ( Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n, ])), Constraints (lockedJoints = ljs), Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ pn, ])),)))) ## Default implementation of ConstraintGraphFactory # # The minimal usage is the following: # \code # graph = ConstraintGraph (robot, "graph") # # # Required calls # factory = ConstraintGraphFactory (graph) # factory.setGrippers (["gripper1", ... ]) # factory.setObjects (["object1", ], [ [ "object1/handle1", ... ] ], [ [] ]) # # # Optionally # factory.environmentContacts (["contact1", ... ]) # factory.setRules ([ Rule (["gripper1", ..], ["handle1", ...], True), ... ]) # # factory.generate () # # graph is initialized # \endcode class ConstraintGraphFactory(GraphFactoryAbstract): class StateAndManifold: def __init__ (self, factory, grasps, id, name): self.grasps = grasps self.id = id self.name = name self.manifold = Constraints() self.foliation = Constraints() # Add the grasps for ig, ih in enumerate(grasps): if ih is not None: self.manifold += factory.constraints.g (ig, ih, 'grasp') self.foliation += factory.constraints.g (ig, ih, 'graspComplement') # Add the placement constraints for io, object in enumerate(factory.objects): if not factory._isObjectGrasped(grasps, io): self.manifold += factory.constraints.p (object, 'placement') self.foliation += factory.constraints.p (object, 'placementComplement') ## \param graph an instance of ConstraintGraph def __init__(self, graph): super (ConstraintGraphFactory, self).__init__() ## Stores the constraints in a child class of ConstraintFactoryAbstract self.constraints = ConstraintFactory (self, graph) self.graph = graph ## \name Default functions # \{ def makeState(self, grasps, priority): # Create state name = self._stateName (grasps) nid = self.graph.createNode (name, False, priority) state = ConstraintGraphFactory.StateAndManifold (self, grasps, nid, name) # Add the constraints self.graph.addConstraints (node = name, constraints = state.manifold) return state def makeLoopTransition(self, state): n = self._loopTransitionName (state.grasps) self.graph.createEdge (state.name, state.name, n, weight = 0, isInNode = state.name) self.graph.addConstraints (edge = n, constraints = state.foliation) def makeTransition(self, stateFrom, stateTo, ig): sf = stateFrom st = stateTo grasps = sf.grasps nGrasps = st.grasps names = self._transitionNames(sf, st, ig) if names in self.transitions: return iobj = self.objectFromHandle [st.grasps[ig]] obj = self.objects[iobj] noPlace = self._isObjectGrasped (sf.grasps, iobj) gc = self.constraints.g (ig, st.grasps[ig], 'grasp') gcc = self.constraints.g (ig, st.grasps[ig], 'graspComplement') pgc = self.constraints.g (ig, st.grasps[ig], 'preGrasp') if noPlace: pc = Constraints() pcc = Constraints() ppc = Constraints() else: pc = self.constraints.p (self.objectFromHandle[st.grasps[ig]], 'placement') pcc = self.constraints.p (self.objectFromHandle[st.grasps[ig]], 'placementComplement') ppc = self.constraints.p (self.objectFromHandle[st.grasps[ig]], 'prePlacement') manifold = sf.manifold - pc # The different cases: pregrasp = not pgc.empty() intersec = (not gc.empty()) and (not pc.empty()) preplace = not ppc.empty() nWaypoints = pregrasp + intersec + preplace nTransitions = 1 + nWaypoints nStates = 2 + nWaypoints def _createWaypointState (name, constraints): self.graph.createNode (name, True) self.graph.addConstraints (node = name, constraints = constraints) return name # Create waypoint states intersection = 0 wStates = [ sf.name, ] if pregrasp: wStates.append (_createWaypointState (names[0] + "_pregrasp", pc + pgc + manifold)) if intersec: wStates.append (_createWaypointState (names[0] + "_intersec", pc + gc + manifold)) if preplace: wStates.append (_createWaypointState (names[0] + "_preplace", ppc + gc + manifold)) wStates.append(st.name) # Link waypoints transitions = names[:] if nWaypoints > 0: self.graph.createWaypointEdge (sf.name, st.name, names[0], nWaypoints, automaticBuilder = False) self.graph.createWaypointEdge (st.name, sf.name, names[1], nWaypoints, automaticBuilder = False) wTransitions = [] for i in range(nTransitions): nf = "{0}_{1}{2}".format(names[0], i, i+1) nb = "{0}_{2}{1}".format(names[1], i, i+1) self.graph.createEdge (wStates[i], wStates[i+1], nf, -1) self.graph.createEdge (wStates[i+1], wStates[i], nb, -1) self.graph.graph.setWaypoint (self.graph.edges[transitions[0]], i, self.graph.edges[nf], self.graph.nodes[wStates[i+1]]) self.graph.graph.setWaypoint (self.graph.edges[transitions[1]], nTransitions - 1 - i, self.graph.edges[nb], self.graph.nodes[wStates[i]]) wTransitions.append ( (nf, nb) ) # Set states M = 0 if gc.empty() else 1 + pregrasp for i in range(M): self.graph.setContainingNode (wTransitions[i][0], sf.name) self.graph.addConstraints (edge = wTransitions[i][0], constraints = sf.foliation) self.graph.setContainingNode (wTransitions[i][1], sf.name) self.graph.addConstraints (edge = wTransitions[i][1], constraints = sf.foliation) for i in range(M, nTransitions): self.graph.setContainingNode (wTransitions[i][0], st.name) self.graph.addConstraints (edge = wTransitions[i][0], constraints = st.foliation) self.graph.setContainingNode (wTransitions[i][1], st.name) self.graph.addConstraints (edge = wTransitions[i][1], constraints = st.foliation) # Set all to short except first one. for i in range(nTransitions - 1): self.graph.setShort (wTransitions[i + 1][0], True) self.graph.setShort (wTransitions[i ][1], True) else: #TODO This case will likely never happen raise NotImplementedError("This case has not been implemented") self.graph.createEdge (sf.name, st.name, names[0]) self.graph.createEdge (st.name, sf.name, names[1]) self.transitions.add(names) ## \} --- FILE SEPARATOR --- #!/usr/bin/env python # Copyright (c) 2014 CNRS # Author: Florent Lamiraux # # This file is part of hpp-manipulation-corba. # hpp-manipulation-corba is free software: you can redistribute it # and/or modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either version # 3 of the License, or (at your option) any later version. # # hpp-manipulation-corba is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Lesser Public License for more details. You should have # received a copy of the GNU Lesser General Public License along with # hpp-manipulation-corba. If not, see # <http://www.gnu.org/licenses/>. import warnings from hpp import Transform from hpp.corbaserver.manipulation import Client as ManipulationClient from hpp.corbaserver import Client as BasicClient from hpp.corbaserver.robot import Robot as Parent ## Corba clients to the various servers # class CorbaClient: """ Container for corba clients to various interfaces. """ def __init__ (self, url = None, context = "corbaserver"): self.basic = BasicClient (url = url, context = context) self.manipulation = ManipulationClient (url = url, context = context) ## Load and handle a composite robot for manipulation planning # # A composite robot is a kinematic chain composed of several sub-kinematic # chains rooted at an anchor joint. class Robot (Parent): ## Constructor # \param robotName name of the first robot that is loaded now, # \param rootJointType type of root joint among ("freeflyer", "planar", # "anchor"), # \param load whether to actually load urdf files. Set to no if you only # want to initialize a corba client to an already initialized # problem. def __init__ (self, compositeName = None, robotName = None, rootJointType = None, load = True, client = None): if client is None: client = CorbaClient() super (Robot, self).__init__ (robotName = compositeName, rootJointType = rootJointType, load = False, client = client, hppcorbaClient = client.basic) self.rootJointType = dict() if compositeName is None: load = False self.load = load self.robotNames = list() if robotName is None: if load: self.client.basic.robot.createRobot (self.name) else: self.loadModel (robotName, rootJointType) ## Virtual function to load the robot model def loadModel (self, robotName, rootJointType): if self.load: self.client.basic.robot.createRobot (self.name) self.insertRobotModel (robotName, rootJointType, self.packageName, self.urdfName, self.urdfSuffix, self.srdfSuffix) ## Load robot model and insert it in the device # # \param robotName key of the robot in hpp::manipulation::ProblemSolver object # map (see hpp::manipulation::ProblemSolver::addRobot) # \param rootJointType type of root joint among "anchor", "freeflyer", # "planar", # \param packageName Name of the ROS package containing the model, # \param modelName Name of the package containing the model # \param urdfSuffix suffix for urdf file, # # The ros url are built as follows: # \li "package://${packageName}/urdf/${modelName}${urdfSuffix}.urdf" # \li "package://${packageName}/srdf/${modelName}${srdfSuffix}.srdf" def insertRobotModel (self, robotName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix): if self.load: self.client.manipulation.robot.insertRobotModel (robotName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix) self.robotNames.append (robotName) self.rootJointType[robotName] = rootJointType self.rebuildRanks () ## Insert robot model as a child of a frame of the Device # # \param robotName key of the robot in ProblemSolver object map # (see hpp::manipulation::ProblemSolver::addRobot) # \param frameName name of the existing frame that will the root of the added robot, # \param rootJointType type of root joint among "anchor", "freeflyer", # "planar", # \param packageName Name of the ROS package containing the model, # \param modelName Name of the package containing the model # \param urdfSuffix suffix for urdf file, # # The ros url are built as follows: # "package://${packageName}/urdf/${modelName}${urdfSuffix}.urdf" # "package://${packageName}/srdf/${modelName}${srdfSuffix}.srdf" # def insertRobotModelOnFrame (self, robotName, frameName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix): if self.load: self.client.manipulation.robot.insertRobotModelOnFrame (robotName, frameName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix) self.robotNames.append (robotName) self.rootJointType[robotName] = rootJointType self.rebuildRanks () ## Same as Robot.insertRobotModel # # \param urdfString XML string of the URDF, # \param srdfString XML string of the SRDF def insertRobotModelFromString (self, robotName, rootJointType, urdfString, srdfString): if self.load: self.client.manipulation.robot.insertRobotModelFromString (robotName, rootJointType, urdfString, srdfString) self.robotNames.append (robotName) self.rootJointType[robotName] = rootJointType self.rebuildRanks () ## Load a SRDF for the robot. Several SRDF can thus be loaded for the same robot # # \param robotName key of the robot in hpp::manipulation::Device object # map (see hpp::manipulation::Device) # \param packageName Name of the ROS package containing the model, # \param modelName Name of the package containing the model # \param srdfSuffix suffix for srdf file, # # The ros url are built as follows: # \li "package://${packageName}/srdf/${modelName}${srdfSuffix}.srdf" def insertRobotSRDFModel (self, robotName, packageName, modelName, srdfSuffix): if self.load: self.client.manipulation.robot.insertRobotSRDFModel (robotName, packageName, modelName, srdfSuffix) ## Load humanoid robot model and insert it in the device # # \param robotName key of the robot in ProblemSolver object map # (see hpp::manipulation::ProblemSolver::addRobot) # \param rootJointType type of root joint among "anchor", "freeflyer", # "planar", # \param packageName Name of the ROS package containing the model, # \param modelName Name of the package containing the model # \param urdfSuffix suffix for urdf file, # # The ros url are built as follows: # \li "package://${packageName}/urdf/${modelName}${urdfSuffix}.urdf" # \li "package://${packageName}/srdf/${modelName}${srdfSuffix}.srdf" def insertHumanoidModel (self, robotName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix): if self.load: self.client.manipulation.robot.insertHumanoidModel \ (robotName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix) self.robotNames.append (robotName) self.rootJointType[robotName] = rootJointType self.rebuildRanks () def loadHumanoidModel (self, robotName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix): self.insertHumanoidModel (robotName, rootJointType, packageName, modelName, urdfSuffix, srdfSuffix) ## Load environment model and store in local map. # Contact surfaces are build from the corresping srdf file. # See hpp-manipulation-urdf for more details about contact surface # specifications. # # \param envName key of the object in ProblemSolver object map # (see hpp::manipulation::ProblemSolver::addRobot) # \param packageName Name of the ROS package containing the model, # \param modelName Name of the package containing the model # \param urdfSuffix suffix for urdf file, # \param srdfSuffix suffix for srdf file. # # The ros url are built as follows: # \li "package://${packageName}/urdf/${modelName}${urdfSuffix}.urdf" # \li "package://${packageName}/srdf/${modelName}${srdfSuffix}.srdf" def loadEnvironmentModel (self, packageName, modelName, urdfSuffix, srdfSuffix, envName): if self.load: self.client.manipulation.robot.loadEnvironmentModel (packageName, modelName, urdfSuffix, srdfSuffix, envName) self.rootJointType[envName] = "Anchor" ## \name Joints #\{ ## Set the position of root joint of a robot in world frame ## \param robotName key of the robot in ProblemSolver object map. ## \param position constant position of the root joint in world frame in ## initial configuration. def setRootJointPosition (self, robotName, position): return self.client.manipulation.robot.setRootJointPosition (robotName, position) ## \} ## \name Bodies # \{ ## Return the joint name in which a gripper is and the position relatively # to the joint def getGripperPositionInJoint (self, gripperName): return self.client.manipulation.robot.getGripperPositionInJoint (gripperName) ## Return the joint name in which a handle is and the position relatively # to the joint def getHandlePositionInJoint (self, handleName): return self.client.manipulation.robot.getHandlePositionInJoint (handleName) ## \} from hpp.corbaserver.robot import StaticStabilityConstraintsFactory class HumanoidRobot (Robot, StaticStabilityConstraintsFactory): ## Constructor # \param compositeName name of the composite robot that will be built later, # \param robotName name of the first robot that is loaded now, # \param rootJointType type of root joint among ("freeflyer", "planar", # "anchor"), def __init__ (self, compositeName = None, robotName = None, rootJointType = None, load = True, client = None): Robot.__init__ (self, compositeName, robotName, rootJointType, load, client) def loadModel (self, robotName, rootJointType): self.client.basic.robot.createRobot (self.name) self.insertHumanoidModel \ (robotName, rootJointType, self.packageName, self.urdfName, self.urdfSuffix, self.srdfSuffix)
{ "imports": [ "/install/lib/python2.7/dist-packages/hpp/corbaserver/manipulation/client.py", "/install/lib/python2.7/dist-packages/hpp/corbaserver/manipulation/problem_solver.py", "/install/lib/python2.7/dist-packages/hpp/corbaserver/manipulation/constraint_graph_factory.py", "/install/lib/python2.7/dist-packages/hpp/corbaserver/manipulation/robot.py" ] }
0023jas/Obelisk-Python-Wallet
refs/heads/main
/obelisk.py
from web3 import Web3 from pubKeyGen import EccMultiply, GPoint from privKeyGen import genPrivKey from walletDecryption import walletDecryption from walletInteractions import getEth from qr import qrGenerate import os import time import glob #Used to store and encrypt wallet from Crypto.Cipher import AES from Crypto.Protocol.KDF import scrypt from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes import json #Used for Bip39Mnemonic from bip_utils import Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44, Bip44Coins, Bip44Changes appRunning = True #Individual Transaction/Personal Information def createWallet(): os.system('cls' if os.name == 'nt' else 'clear') print(" ╔═╗┌─┐┌┐┌┌─┐┬─┐┌─┐┌┬┐┌─┐ ╦ ╦┌─┐┬ ┬ ┌─┐┌┬┐") print(" ║ ╦├┤ │││├┤ ├┬┘├─┤ │ ├┤ ║║║├─┤│ │ ├┤ │ ") print(" ╚═╝└─┘┘└┘└─┘┴└─┴ ┴ ┴ └─┘ ╚╩╝┴ ┴┴─┘┴─┘└─┘ ┴ ") print("") print(" ############################################") print("") print(" > Please Input a Secure Password") print("") password = input(" > ") time.sleep(2) print("") print(" > Generating Wallet") privKey = genPrivKey() PublicKey = EccMultiply(GPoint,privKey) PublicKey = hex(PublicKey[0])[2:] + hex(PublicKey[1])[2:] address = Web3.keccak(hexstr = PublicKey).hex() address = "0x" + address[-40:] address = Web3.toChecksumAddress(address) time.sleep(2) print("") print(" > Encrypting Wallet") salt = get_random_bytes(16) key = scrypt(password, salt, 32, N=2**20, r = 8, p = 1) privKey = hex(privKey)[2:] data = str(privKey).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data, AES.block_size)) salt = salt.hex() iv = cipher.iv.hex() ct = ct_bytes.hex() output = {"salt" : salt, "initialization vector" : iv, "encrypted private key" : ct} with open("wallets/" + address + '.txt', 'w') as json_file: json.dump(output, json_file) qrGenerate(address) print("") print(" > Wallet Created") time.sleep(2) print("") print(" > Do you want to return to the home screen [y/n]?") print("") userInput = input(" > ") print("") userInputCheck = False while userInputCheck == False: if userInput == 'y': userInputCheck = True return True elif userInput == 'n': userInputCheck = True return False else: print(" > Only y and n are correct inputs") def decodeWallet(): walletSelect = False while walletSelect == False: os.system('cls' if os.name == 'nt' else 'clear') print(" ╔═╗┌─┐┬ ┌─┐┌─┐┌┬┐ ╦ ╦┌─┐┬ ┬ ┌─┐┌┬┐") print(" ╚═╗├┤ │ ├┤ │ │ ║║║├─┤│ │ ├┤ │") print(" ╚═╝└─┘┴─┘└─┘└─┘ ┴ ╚╩╝┴ ┴┴─┘┴─┘└─┘ ┴") print("") print(" ######################################") print("") availableWallets = os.listdir("wallets") for wallet in range(len(availableWallets)): print(" " + str(wallet+1) + ": " + availableWallets[wallet][:-4]) print("") walletSelector = input(" > ") if 0 < int(walletSelector) <= len(availableWallets): walletName = availableWallets[int(walletSelector)-1] with open("wallets/" + walletName) as f: data = json.load(f) #print(data) """ print(" Enter Password:") print("") password = input(" > ") """ address = walletName[:-4] walletSelect = True walletDecryption(data, address) return True def migrateWallet(): os.system('cls' if os.name == 'nt' else 'clear') print(" ╔╦╗┬┌─┐┬─┐┌─┐┌┬┐┌─┐ ╦ ╦┌─┐┬ ┬ ┌─┐┌┬┐") print(" ║║║││ ┬├┬┘├─┤ │ ├┤ ║║║├─┤│ │ ├┤ │ ") print(" ╩ ╩┴└─┘┴└─┴ ┴ ┴ └─┘ ╚╩╝┴ ┴┴─┘┴─┘└─┘ ┴ ") print("") print(" #######################################") print("") print(" 1: Migrate Through Private Key") print("") print(" 2: Migrate Through 12 Word Phrase") print("") userInput = input(" > ") print("") if userInput == "1": print(" Type Private Key:") print("") privKey = input(" > ") privKey = int(privKey, 16) print("") print(" Type Strong Password:") print("") password = input(" > ") PublicKey = EccMultiply(GPoint, privKey) PublicKey = hex(PublicKey[0])[2:] + hex(PublicKey[1])[2:] address = Web3.keccak(hexstr = PublicKey).hex() address = "0x" + address[-40:] address = Web3.toChecksumAddress(address) time.sleep(2) print("") print("> Encrypting Wallet") salt = get_random_bytes(16) key = scrypt(password, salt, 32, N=2**20, r = 8, p = 1) privKey = hex(privKey)[2:] data = str(privKey).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data, AES.block_size)) salt = salt.hex() iv = cipher.iv.hex() ct = ct_bytes.hex() output = {"salt" : salt, "initialization vector" : iv, "encrypted private key" : ct} with open("wallets/" + address + '.txt', 'w') as json_file: json.dump(output, json_file) print("") print("> Wallet Created") time.sleep(2) startWallet() elif userInput == "2": print(" Type 12 Words:") mnemonic = input(" > ") seed_bytes = Bip39SeedGenerator(mnemonic).Generate() bip_obj_mst = Bip44.FromSeed(seed_bytes, Bip44Coins.ETHEREUM) bip_obj_acc = bip_obj_mst.Purpose().Coin().Account(0) bip_obj_chain = bip_obj_acc.Change(Bip44Changes.CHAIN_EXT) accountFound = False accountNumber = 0 while accountFound == False: bip_obj_addr = bip_obj_chain.AddressIndex(accountNumber) checkAddress = getEth(bip_obj_addr.PublicKey().ToAddress()) if checkAddress > 0: accountFound = True privKey = bip_obj_addr.PrivateKey().Raw().ToHex() privKey = int(privKey, 16) print("") print(" > Found Wallet!") time.sleep(2) print("") print(" Type Strong Password:") print("") password = input(" > ") PublicKey = EccMultiply(GPoint, privKey) PublicKey = hex(PublicKey[0])[2:] + hex(PublicKey[1])[2:] address = Web3.keccak(hexstr = PublicKey).hex() address = "0x" + address[-40:] address = Web3.toChecksumAddress(address) time.sleep(2) print("") print("> Encrypting Wallet") salt = get_random_bytes(16) key = scrypt(password, salt, 32, N=2**20, r = 8, p = 1) privKey = hex(privKey)[2:] data = str(privKey).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data, AES.block_size)) salt = salt.hex() iv = cipher.iv.hex() ct = ct_bytes.hex() output = {"salt" : salt, "initialization vector" : iv, "encrypted private key" : ct} with open("wallets/" + address + '.txt', 'w') as json_file: json.dump(output, json_file) print("") print("> Wallet Created") time.sleep(2) startWallet() def startWallet(): userOption = False while(userOption == False): os.system('cls' if os.name == 'nt' else 'clear') print("") print(" ██████╗ ██████╗ ███████╗██╗ ██╗███████╗██╗ ██╗") print(" ██╔═══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██║ ██╔╝") print(" ██║ ██║██████╔╝█████╗ ██║ ██║███████╗█████╔╝ ") print(" ██║ ██║██╔══██╗██╔══╝ ██║ ██║╚════██║██╔═██╗ ") print(" ╚██████╔╝██████╔╝███████╗███████╗██║███████║██║ ██╗") print(" ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚═╝╚══════╝╚═╝ ╚═╝") print("") print(" ####################################################") print("") print(" 1: Access Saved Wallet") print("") print(" 2: Generate New Wallet") print("") print(" 3: Migrate Wallet") print("") print(" 4: Exit Obelisk") print("") userInput = input(" > ") if userInput != "1" and userInput != "2" and userInput != "3" and userInput != "4": os.system('cls' if os.name == 'nt' else 'clear') print("") print(" > Oops, wrong input!") print("") print(" > 1, 2, 3, or 4 is the only acceptable input") print("") print(" > Hit enter to continue") print("") errorInput = input(" > ") else: userOption = True print(userOption) if userInput == "1": appStatus = decodeWallet() return appStatus elif userInput == "2": appStatus = createWallet() return appStatus elif userInput == "3": migrateWallet() elif userInput == "4": os.system('cls' if os.name == 'nt' else 'clear') return False while appRunning == True: appRunning = startWallet()
from random import randint def genPrivKey(): N=int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16) private_key = randint(1, N) return private_key --- FILE SEPARATOR --- from Crypto.Cipher import AES from Crypto.Protocol.KDF import scrypt from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes import json import time import os from walletInteractions import sendEth, getEth, receiveEth from currencyConvert import weiToEth #Used to run getWalletStats import requests from bs4 import BeautifulSoup import re import requests def getWalletStats(): statsList = [] #Get Ethereum Value ethLink = requests.get('https://coinmarketcap.com/currencies/ethereum/') ethSoup = BeautifulSoup(ethLink.content, 'html.parser') ethPrice = ethSoup.findAll('td') ethPrice = ethPrice[0].contents ethPrice = re.sub('\ USD$', '', ethPrice[0]) ethPrice = ethPrice[1:] ethPrice = float(ethPrice.replace(',','')) statsList.append(ethPrice) #Get Low, Medium, and High Gas Fees gasLink = requests.get('https://ethgasstation.info/') gasSoup = BeautifulSoup(gasLink.content, 'html.parser') lowFee = gasSoup.find('div', {'class':'safe_low'}) avgFee = gasSoup.find('div', {'class':'standard'}) highFee = gasSoup.find('div', {'class':'fast'}) statsList.append(int(lowFee.contents[0])) statsList.append(int(avgFee.contents[0])) statsList.append(int(highFee.contents[0])) return statsList def runWallet(privateKey, address): userQuit = False while userQuit == False: os.system('cls' if os.name == 'nt' else 'clear') ethStats = getWalletStats() walletEthereumValue = round(weiToEth(getEth(address)), 6) walletDollarValue = round(walletEthereumValue * ethStats[0], 2) lowGas = ethStats[1] avgGas = ethStats[2] highGas = ethStats[3] print("") print(" ╔═╗┌┐ ┌─┐┬ ┬┌─┐┬┌─ ╦ ╦┌─┐┬ ┬ ┌─┐┌┬┐") print(" ║ ║├┴┐├┤ │ │└─┐├┴┐ ║║║├─┤│ │ ├┤ │ ") print(" ╚═╝└─┘└─┘┴─┘┴└─┘┴ ┴ ╚╩╝┴ ┴┴─┘┴─┘└─┘ ┴ ") print("") print(" #######################################") print("") print(" Address: " + address) print(" Ethereum Value: Ξ" + str(walletEthereumValue)) print(" Dollar Value: $" + str(walletDollarValue)) print("") print(" Current Gas Prices in Gwei:") print(" Low: " + str(lowGas) + ", Average: " + str(avgGas) + ", High: " + str(highGas)) print("") print(" Actions: ") print(" 1: Send") print(" 2: Receive") print(" 3: Exit") print("") userInput = input(" > ") if userInput == "1": sendEth(privateKey, address) elif userInput == "2": receiveEth(address) elif userInput == "3": os.system('cls' if os.name == 'nt' else 'clear') userQuit = True def walletDecryption(data, address): correctPassword = False while correctPassword == False: print("") print(" Enter Password or type n to return:") print("") password = input(" > ") salt = data['salt'] iv = data['initialization vector'] ct = data['encrypted private key'] salt = bytes.fromhex(salt) iv = bytes.fromhex(iv) ct = bytes.fromhex(ct) key = scrypt(password, salt, 32, N = 2**20, r = 8, p = 1) cipher = AES.new(key, AES.MODE_CBC, iv) try: pt = unpad(cipher.decrypt(ct), AES.block_size) privateKey = pt.decode('utf-8') #print(privateKey) #time.sleep(5) correctPassword = True runWallet(privateKey, address) except: if password == 'n': correctPassword = True print("") print(" > Returning to home") time.sleep(2) else: print("") print(" > wrong password entered") time.sleep(2) --- FILE SEPARATOR --- from web3 import Web3 from PIL import Image from currencyConvert import ethToWei, gweiToWei import time w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/5d6be6c002c744358836ac43f459d453')) def getEth(address): return w3.eth.get_balance(address) def sendEth(privateKey, address): #Typed as String must Remain String print("") print(" Enter the Receiver Address:") receiveAddress = input(" > ") #Typed in Eth needs to be Wei print("") print(" Enter the Amount you Want to Send in Eth:") sendAmount = int(ethToWei(float(input(" > ")))) #print(sendAmount) #Typed in Gwei needs to be wei print("") print(" Type Gas Fee in Gwei:") gasFee = gweiToWei(int(input(" > "))) signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(address), gasPrice=gasFee, gas=21000, to=receiveAddress, value=sendAmount, data=b'', ), privateKey, ) w3.eth.sendRawTransaction(signed_txn.rawTransaction) print("") print("Your transaction is sent! check it out here: etherscan.io/address/"+address) time.sleep(10) def receiveEth(address): print("") print(" Wallet Address: " + address) print("") image = Image.open('qr/' + address + ".png") image.show() time.sleep(5) --- FILE SEPARATOR --- import qrcode #Takes in Address, Saves QR in /qr def qrGenerate(inputAddress): addressName = inputAddress img = qrcode.make(addressName) img.save("qr/" + addressName + '.png') return addressName
{ "imports": [ "/privKeyGen.py", "/walletDecryption.py", "/walletInteractions.py", "/qr.py" ] }
0023jas/Obelisk-Python-Wallet
refs/heads/main
/walletDecryption.py
from Crypto.Cipher import AES from Crypto.Protocol.KDF import scrypt from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes import json import time import os from walletInteractions import sendEth, getEth, receiveEth from currencyConvert import weiToEth #Used to run getWalletStats import requests from bs4 import BeautifulSoup import re import requests def getWalletStats(): statsList = [] #Get Ethereum Value ethLink = requests.get('https://coinmarketcap.com/currencies/ethereum/') ethSoup = BeautifulSoup(ethLink.content, 'html.parser') ethPrice = ethSoup.findAll('td') ethPrice = ethPrice[0].contents ethPrice = re.sub('\ USD$', '', ethPrice[0]) ethPrice = ethPrice[1:] ethPrice = float(ethPrice.replace(',','')) statsList.append(ethPrice) #Get Low, Medium, and High Gas Fees gasLink = requests.get('https://ethgasstation.info/') gasSoup = BeautifulSoup(gasLink.content, 'html.parser') lowFee = gasSoup.find('div', {'class':'safe_low'}) avgFee = gasSoup.find('div', {'class':'standard'}) highFee = gasSoup.find('div', {'class':'fast'}) statsList.append(int(lowFee.contents[0])) statsList.append(int(avgFee.contents[0])) statsList.append(int(highFee.contents[0])) return statsList def runWallet(privateKey, address): userQuit = False while userQuit == False: os.system('cls' if os.name == 'nt' else 'clear') ethStats = getWalletStats() walletEthereumValue = round(weiToEth(getEth(address)), 6) walletDollarValue = round(walletEthereumValue * ethStats[0], 2) lowGas = ethStats[1] avgGas = ethStats[2] highGas = ethStats[3] print("") print(" ╔═╗┌┐ ┌─┐┬ ┬┌─┐┬┌─ ╦ ╦┌─┐┬ ┬ ┌─┐┌┬┐") print(" ║ ║├┴┐├┤ │ │└─┐├┴┐ ║║║├─┤│ │ ├┤ │ ") print(" ╚═╝└─┘└─┘┴─┘┴└─┘┴ ┴ ╚╩╝┴ ┴┴─┘┴─┘└─┘ ┴ ") print("") print(" #######################################") print("") print(" Address: " + address) print(" Ethereum Value: Ξ" + str(walletEthereumValue)) print(" Dollar Value: $" + str(walletDollarValue)) print("") print(" Current Gas Prices in Gwei:") print(" Low: " + str(lowGas) + ", Average: " + str(avgGas) + ", High: " + str(highGas)) print("") print(" Actions: ") print(" 1: Send") print(" 2: Receive") print(" 3: Exit") print("") userInput = input(" > ") if userInput == "1": sendEth(privateKey, address) elif userInput == "2": receiveEth(address) elif userInput == "3": os.system('cls' if os.name == 'nt' else 'clear') userQuit = True def walletDecryption(data, address): correctPassword = False while correctPassword == False: print("") print(" Enter Password or type n to return:") print("") password = input(" > ") salt = data['salt'] iv = data['initialization vector'] ct = data['encrypted private key'] salt = bytes.fromhex(salt) iv = bytes.fromhex(iv) ct = bytes.fromhex(ct) key = scrypt(password, salt, 32, N = 2**20, r = 8, p = 1) cipher = AES.new(key, AES.MODE_CBC, iv) try: pt = unpad(cipher.decrypt(ct), AES.block_size) privateKey = pt.decode('utf-8') #print(privateKey) #time.sleep(5) correctPassword = True runWallet(privateKey, address) except: if password == 'n': correctPassword = True print("") print(" > Returning to home") time.sleep(2) else: print("") print(" > wrong password entered") time.sleep(2)
from web3 import Web3 from PIL import Image from currencyConvert import ethToWei, gweiToWei import time w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/5d6be6c002c744358836ac43f459d453')) def getEth(address): return w3.eth.get_balance(address) def sendEth(privateKey, address): #Typed as String must Remain String print("") print(" Enter the Receiver Address:") receiveAddress = input(" > ") #Typed in Eth needs to be Wei print("") print(" Enter the Amount you Want to Send in Eth:") sendAmount = int(ethToWei(float(input(" > ")))) #print(sendAmount) #Typed in Gwei needs to be wei print("") print(" Type Gas Fee in Gwei:") gasFee = gweiToWei(int(input(" > "))) signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(address), gasPrice=gasFee, gas=21000, to=receiveAddress, value=sendAmount, data=b'', ), privateKey, ) w3.eth.sendRawTransaction(signed_txn.rawTransaction) print("") print("Your transaction is sent! check it out here: etherscan.io/address/"+address) time.sleep(10) def receiveEth(address): print("") print(" Wallet Address: " + address) print("") image = Image.open('qr/' + address + ".png") image.show() time.sleep(5) --- FILE SEPARATOR --- def weiToEth(amount): amount = amount/1000000000000000000 return amount def ethToWei(amount): amount = amount*1000000000000000000 return amount def gweiToWei(amount): amount = amount*1000000000 return amount
{ "imports": [ "/walletInteractions.py", "/currencyConvert.py" ] }
0023jas/Obelisk-Python-Wallet
refs/heads/main
/walletInteractions.py
from web3 import Web3 from PIL import Image from currencyConvert import ethToWei, gweiToWei import time w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/5d6be6c002c744358836ac43f459d453')) def getEth(address): return w3.eth.get_balance(address) def sendEth(privateKey, address): #Typed as String must Remain String print("") print(" Enter the Receiver Address:") receiveAddress = input(" > ") #Typed in Eth needs to be Wei print("") print(" Enter the Amount you Want to Send in Eth:") sendAmount = int(ethToWei(float(input(" > ")))) #print(sendAmount) #Typed in Gwei needs to be wei print("") print(" Type Gas Fee in Gwei:") gasFee = gweiToWei(int(input(" > "))) signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(address), gasPrice=gasFee, gas=21000, to=receiveAddress, value=sendAmount, data=b'', ), privateKey, ) w3.eth.sendRawTransaction(signed_txn.rawTransaction) print("") print("Your transaction is sent! check it out here: etherscan.io/address/"+address) time.sleep(10) def receiveEth(address): print("") print(" Wallet Address: " + address) print("") image = Image.open('qr/' + address + ".png") image.show() time.sleep(5)
def weiToEth(amount): amount = amount/1000000000000000000 return amount def ethToWei(amount): amount = amount*1000000000000000000 return amount def gweiToWei(amount): amount = amount*1000000000 return amount
{ "imports": [ "/currencyConvert.py" ] }
007Rohan/Project-Management-using-REST-API-DJANGO
refs/heads/main
/app/serializer.py
from rest_framework import serializers from .models import addClient,addProject from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username'] class ClientSerializer(serializers.ModelSerializer): class Meta: model=addClient fields=['id','client_name','created_at','created_by'] class ClientProjectSerializer(serializers.ModelSerializer): contributed_users = UserSerializer(many=True) class Meta: model=addProject fields='__all__' class ClientProjectSerializer1(serializers.ModelSerializer): class Meta: model=addProject fields='__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model=addProject fields=['id','project_name','created_at','created_by_client']
from django.db import models from django.contrib.auth.models import User # Create your models here. class addClient(models.Model): id=models.AutoField(primary_key=True) client_name=models.CharField(max_length=30) created_at=models.DateTimeField(auto_now_add=True) created_by=models.ForeignKey(User,on_delete=models.CASCADE) objects=models.Manager() def __str__(self): return self.client_name class Meta: db_table='addclients' class addProject(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=100) contributed_users=models.ManyToManyField(User) created_at=models.DateTimeField(auto_now_add=True) created_by_client=models.ForeignKey(addClient,unique=False,on_delete=models.CASCADE) objects=models.Manager() class Meta: db_table='addprojects'
{ "imports": [ "/app/models.py" ] }
007Rohan/Project-Management-using-REST-API-DJANGO
refs/heads/main
/app/views.py
from django.shortcuts import render,HttpResponse from rest_framework import generics from .models import addClient,addProject from .serializer import ClientSerializer,ProjectSerializer,ClientProjectSerializer,ClientProjectSerializer1 # Create your views here. def home(request): return render(request,"index.html") class AddClient(generics.CreateAPIView): serializer_class=ClientSerializer class AddProject(generics.CreateAPIView): serializer_class=ClientProjectSerializer1 class ClientList(generics.ListAPIView): queryset=addClient.objects.all() serializer_class=ClientSerializer class DeleteClient(generics.DestroyAPIView): queryset=addClient.objects.all() serializer_class=ClientSerializer class ProjectList(generics.ListAPIView): queryset=addProject.objects.all() serializer_class=ProjectSerializer class ClientProjectList(generics.ListAPIView): queryset=addProject.objects.all() serializer_class=ClientProjectSerializer
from django.db import models from django.contrib.auth.models import User # Create your models here. class addClient(models.Model): id=models.AutoField(primary_key=True) client_name=models.CharField(max_length=30) created_at=models.DateTimeField(auto_now_add=True) created_by=models.ForeignKey(User,on_delete=models.CASCADE) objects=models.Manager() def __str__(self): return self.client_name class Meta: db_table='addclients' class addProject(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=100) contributed_users=models.ManyToManyField(User) created_at=models.DateTimeField(auto_now_add=True) created_by_client=models.ForeignKey(addClient,unique=False,on_delete=models.CASCADE) objects=models.Manager() class Meta: db_table='addprojects' --- FILE SEPARATOR --- from rest_framework import serializers from .models import addClient,addProject from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username'] class ClientSerializer(serializers.ModelSerializer): class Meta: model=addClient fields=['id','client_name','created_at','created_by'] class ClientProjectSerializer(serializers.ModelSerializer): contributed_users = UserSerializer(many=True) class Meta: model=addProject fields='__all__' class ClientProjectSerializer1(serializers.ModelSerializer): class Meta: model=addProject fields='__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model=addProject fields=['id','project_name','created_at','created_by_client']
{ "imports": [ "/app/models.py", "/app/serializer.py" ] }
007gzs/xface
refs/heads/master
/xface/model/__init__.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals from .face_alignment import FaceAlignment from .face_detection import FaceDetector from .face_recognition import FaceRecognition __all__ = ['FaceAlignment', 'FaceDetector', 'FaceRecognition']
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import cv2 import torch import numpy as np import torch.backends.cudnn as cudnn from torchvision import transforms from .base import Base class FaceAlignment(Base): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.img_size = self.meta_conf['input_width'] def get(self, image, det): cudnn.benchmark = True assert isinstance(image, np.ndarray) img = image.copy() img = np.float32(img) xy = np.array([det[0], det[1]]) zz = np.array([det[2], det[3]]) wh = zz - xy + 1 center = (xy + wh / 2).astype(np.int32) box_size = int(np.max(wh) * 1.2) xy = center - box_size // 2 x1, y1 = xy x2, y2 = xy + box_size height, width, _ = img.shape dx = max(0, -x1) dy = max(0, -y1) x1 = max(0, x1) y1 = max(0, y1) edx = max(0, x2 - width) edy = max(0, y2 - height) x2 = min(width, x2) y2 = min(height, y2) image_t = image[y1:y2, x1:x2] if dx > 0 or dy > 0 or edx > 0 or edy > 0: image_t = cv2.copyMakeBorder(image_t, dy, edy, dx, edx, cv2.BORDER_CONSTANT, 0) image_t = cv2.resize(image_t, (self.img_size, self.img_size)) t = transforms.Compose([transforms.ToTensor()]) img_after = t(image_t) self.model = self.model.to(self.device) img_after = img_after.unsqueeze(0) with torch.no_grad(): image_pre = img_after.to(self.device) _, landmarks_normal = self.model(image_pre) landmarks_normal = landmarks_normal.cpu().numpy() landmarks_normal = landmarks_normal.reshape(landmarks_normal.shape[0], -1, 2) landmarks = landmarks_normal[0] * [box_size, box_size] + xy return landmarks --- FILE SEPARATOR --- # encoding: utf-8 from __future__ import absolute_import, unicode_literals from itertools import product from math import ceil import numpy as np import torch import torch.backends.cudnn as cudnn from .base import Base class FaceDetector(Base): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.min_sizes = self.meta_conf['min_sizes'] self.steps = self.meta_conf['steps'] self.variance = self.meta_conf['variance'] self.in_channel = self.meta_conf['in_channel'] self.out_channel = self.meta_conf['out_channel'] self.confidence_threshold = self.meta_conf['confidence_threshold'] def detect(self, image): cudnn.benchmark = True assert isinstance(image, np.ndarray) input_height, input_width, _ = image.shape img = np.float32(image) scale_box = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]]) img -= (104, 117, 123) img = img.transpose(2, 0, 1) self.model = self.model.to(self.device) img = torch.from_numpy(img).unsqueeze(0) scale_landms = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2]]) with torch.no_grad(): img = img.to(self.device) scale_box = scale_box.to(self.device) scale_landms = scale_landms.to(self.device) loc, conf, landms = self.model(img) priors = self.priorbox_forward(height=input_height, width=input_width) priors = priors.to(self.device) prior_data = priors.data boxes = self.decode(loc.data.squeeze(0), prior_data, self.variance) boxes = boxes * scale_box boxes = boxes.cpu().numpy() scores = conf.squeeze(0).data.cpu().numpy()[:, 1] landmarks = self.decode_landm(landms.data.squeeze(0), prior_data, self.variance) landmarks = landmarks * scale_landms landmarks = landmarks.reshape((landmarks.shape[0], 5, 2)) landmarks = landmarks.cpu().numpy() # ignore low scores inds = np.where(scores > self.confidence_threshold)[0] boxes = boxes[inds] scores = scores[inds] landmarks = landmarks[inds] # keep top-K before NMS order = scores.argsort()[::-1] boxes = boxes[order] scores = scores[order] landmarks = landmarks[order] # do NMS nms_threshold = 0.2 dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False) keep = self.py_cpu_nms(dets, nms_threshold) dets = dets[keep, :] landmarks = landmarks[keep] return dets, landmarks def py_cpu_nms(self, dets, thresh): """ Python version NMS. Returns: The kept index after NMS. """ x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep # Adapted from https://github.com/Hakuyume/chainer-ssd def decode(self, loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """ boxes = torch.cat(( priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) boxes[:, :2] -= boxes[:, 2:] / 2 boxes[:, 2:] += boxes[:, :2] return boxes def decode_landm(self, pre, priors, variances): """Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded landm predictions """ landms = torch.cat((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], ), dim=1) return landms # https://github.com/biubug6/Pytorch_Retinaface def priorbox_forward(self, height, width): feature_maps = [[ceil(height / step), ceil(width / step)] for step in self.steps] anchors = [] for k, f in enumerate(feature_maps): min_sizes = self.min_sizes[k] for i, j in product(range(f[0]), range(f[1])): for min_size in min_sizes: s_kx = min_size / width s_ky = min_size / height dense_cx = [x * self.steps[k] / width for x in [j + 0.5]] dense_cy = [y * self.steps[k] / height for y in [i + 0.5]] for cy, cx in product(dense_cy, dense_cx): anchors += [cx, cy, s_kx, s_ky] return torch.Tensor(anchors).view(-1, 4) --- FILE SEPARATOR --- # encoding: utf-8 from __future__ import absolute_import, unicode_literals import numpy as np import torch from .base import Base class FaceRecognition(Base): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.mean = self.meta_conf['mean'] self.std = self.meta_conf['std'] def load(self, device=None): super().load(device) if self.device.type == "cpu": self.model = self.model.module.cpu() def get(self, image): assert isinstance(image, np.ndarray) height, width, channels = image.shape assert height == self.input_height and width == self.input_width if image.ndim == 2: image = image[:, :, np.newaxis] if image.ndim == 4: image = image[:, :, :3] assert image.ndim <= 4 image = (image.transpose((2, 0, 1)) - self.mean) / self.std image = image.astype(np.float32) image = torch.from_numpy(image) image = torch.unsqueeze(image, 0) image = image.to(self.device) with torch.no_grad(): feature = self.model(image).cpu().numpy() feature = np.squeeze(feature) return feature
{ "imports": [ "/xface/model/face_alignment.py", "/xface/model/face_detection.py", "/xface/model/face_recognition.py" ] }
007gzs/xface
refs/heads/master
/xface/model/face_recognition.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import numpy as np import torch from .base import Base class FaceRecognition(Base): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.mean = self.meta_conf['mean'] self.std = self.meta_conf['std'] def load(self, device=None): super().load(device) if self.device.type == "cpu": self.model = self.model.module.cpu() def get(self, image): assert isinstance(image, np.ndarray) height, width, channels = image.shape assert height == self.input_height and width == self.input_width if image.ndim == 2: image = image[:, :, np.newaxis] if image.ndim == 4: image = image[:, :, :3] assert image.ndim <= 4 image = (image.transpose((2, 0, 1)) - self.mean) / self.std image = image.astype(np.float32) image = torch.from_numpy(image) image = torch.unsqueeze(image, 0) image = image.to(self.device) with torch.no_grad(): feature = self.model(image).cpu().numpy() feature = np.squeeze(feature) return feature
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import json import os import sys import torch class Config(dict): def __getattr__(self, key): if key in self: return self[key] return None def __setattr__(self, key, value): self[key] = value class Base: def __init__(self, model_path, model_category, model_name, meta_file='model_meta.json'): model_root_dir = os.path.join(model_path, model_category, model_name) meta_file_path = os.path.join(model_root_dir, meta_file) with open(meta_file_path, 'r') as f: self.meta_conf = json.load(f) model_root = os.path.dirname(model_path) if model_root not in sys.path: sys.path.append(model_root) self.model_path = model_path self.model_category = model_category self.model_name = model_name self.model_file_path = os.path.join(model_root_dir, self.meta_conf['model_file']) self.model_type = self.meta_conf['model_type'] self.model_info = self.meta_conf['model_info'] self.release_date = self.meta_conf['release_date'] self.input_height = self.meta_conf['input_height'] self.input_width = self.meta_conf['input_width'] self.device = None self.model = None def load(self, device=None): assert self.model is None if device is None: if torch.cuda.is_available(): device = "cuda:%d" % torch.cuda.current_device() else: device = "cpu" self.device = torch.device(device) self.model = torch.load(self.model_file_path, map_location=self.device) self.model.eval()
{ "imports": [ "/xface/model/base.py" ] }
007gzs/xface
refs/heads/master
/xface/model/face_alignment.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import cv2 import torch import numpy as np import torch.backends.cudnn as cudnn from torchvision import transforms from .base import Base class FaceAlignment(Base): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.img_size = self.meta_conf['input_width'] def get(self, image, det): cudnn.benchmark = True assert isinstance(image, np.ndarray) img = image.copy() img = np.float32(img) xy = np.array([det[0], det[1]]) zz = np.array([det[2], det[3]]) wh = zz - xy + 1 center = (xy + wh / 2).astype(np.int32) box_size = int(np.max(wh) * 1.2) xy = center - box_size // 2 x1, y1 = xy x2, y2 = xy + box_size height, width, _ = img.shape dx = max(0, -x1) dy = max(0, -y1) x1 = max(0, x1) y1 = max(0, y1) edx = max(0, x2 - width) edy = max(0, y2 - height) x2 = min(width, x2) y2 = min(height, y2) image_t = image[y1:y2, x1:x2] if dx > 0 or dy > 0 or edx > 0 or edy > 0: image_t = cv2.copyMakeBorder(image_t, dy, edy, dx, edx, cv2.BORDER_CONSTANT, 0) image_t = cv2.resize(image_t, (self.img_size, self.img_size)) t = transforms.Compose([transforms.ToTensor()]) img_after = t(image_t) self.model = self.model.to(self.device) img_after = img_after.unsqueeze(0) with torch.no_grad(): image_pre = img_after.to(self.device) _, landmarks_normal = self.model(image_pre) landmarks_normal = landmarks_normal.cpu().numpy() landmarks_normal = landmarks_normal.reshape(landmarks_normal.shape[0], -1, 2) landmarks = landmarks_normal[0] * [box_size, box_size] + xy return landmarks
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import json import os import sys import torch class Config(dict): def __getattr__(self, key): if key in self: return self[key] return None def __setattr__(self, key, value): self[key] = value class Base: def __init__(self, model_path, model_category, model_name, meta_file='model_meta.json'): model_root_dir = os.path.join(model_path, model_category, model_name) meta_file_path = os.path.join(model_root_dir, meta_file) with open(meta_file_path, 'r') as f: self.meta_conf = json.load(f) model_root = os.path.dirname(model_path) if model_root not in sys.path: sys.path.append(model_root) self.model_path = model_path self.model_category = model_category self.model_name = model_name self.model_file_path = os.path.join(model_root_dir, self.meta_conf['model_file']) self.model_type = self.meta_conf['model_type'] self.model_info = self.meta_conf['model_info'] self.release_date = self.meta_conf['release_date'] self.input_height = self.meta_conf['input_height'] self.input_width = self.meta_conf['input_width'] self.device = None self.model = None def load(self, device=None): assert self.model is None if device is None: if torch.cuda.is_available(): device = "cuda:%d" % torch.cuda.current_device() else: device = "cpu" self.device = torch.device(device) self.model = torch.load(self.model_file_path, map_location=self.device) self.model.eval()
{ "imports": [ "/xface/model/base.py" ] }
007gzs/xface
refs/heads/master
/xface/model/face_detection.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals from itertools import product from math import ceil import numpy as np import torch import torch.backends.cudnn as cudnn from .base import Base class FaceDetector(Base): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.min_sizes = self.meta_conf['min_sizes'] self.steps = self.meta_conf['steps'] self.variance = self.meta_conf['variance'] self.in_channel = self.meta_conf['in_channel'] self.out_channel = self.meta_conf['out_channel'] self.confidence_threshold = self.meta_conf['confidence_threshold'] def detect(self, image): cudnn.benchmark = True assert isinstance(image, np.ndarray) input_height, input_width, _ = image.shape img = np.float32(image) scale_box = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]]) img -= (104, 117, 123) img = img.transpose(2, 0, 1) self.model = self.model.to(self.device) img = torch.from_numpy(img).unsqueeze(0) scale_landms = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2]]) with torch.no_grad(): img = img.to(self.device) scale_box = scale_box.to(self.device) scale_landms = scale_landms.to(self.device) loc, conf, landms = self.model(img) priors = self.priorbox_forward(height=input_height, width=input_width) priors = priors.to(self.device) prior_data = priors.data boxes = self.decode(loc.data.squeeze(0), prior_data, self.variance) boxes = boxes * scale_box boxes = boxes.cpu().numpy() scores = conf.squeeze(0).data.cpu().numpy()[:, 1] landmarks = self.decode_landm(landms.data.squeeze(0), prior_data, self.variance) landmarks = landmarks * scale_landms landmarks = landmarks.reshape((landmarks.shape[0], 5, 2)) landmarks = landmarks.cpu().numpy() # ignore low scores inds = np.where(scores > self.confidence_threshold)[0] boxes = boxes[inds] scores = scores[inds] landmarks = landmarks[inds] # keep top-K before NMS order = scores.argsort()[::-1] boxes = boxes[order] scores = scores[order] landmarks = landmarks[order] # do NMS nms_threshold = 0.2 dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False) keep = self.py_cpu_nms(dets, nms_threshold) dets = dets[keep, :] landmarks = landmarks[keep] return dets, landmarks def py_cpu_nms(self, dets, thresh): """ Python version NMS. Returns: The kept index after NMS. """ x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep # Adapted from https://github.com/Hakuyume/chainer-ssd def decode(self, loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """ boxes = torch.cat(( priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) boxes[:, :2] -= boxes[:, 2:] / 2 boxes[:, 2:] += boxes[:, :2] return boxes def decode_landm(self, pre, priors, variances): """Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded landm predictions """ landms = torch.cat((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], ), dim=1) return landms # https://github.com/biubug6/Pytorch_Retinaface def priorbox_forward(self, height, width): feature_maps = [[ceil(height / step), ceil(width / step)] for step in self.steps] anchors = [] for k, f in enumerate(feature_maps): min_sizes = self.min_sizes[k] for i, j in product(range(f[0]), range(f[1])): for min_size in min_sizes: s_kx = min_size / width s_ky = min_size / height dense_cx = [x * self.steps[k] / width for x in [j + 0.5]] dense_cy = [y * self.steps[k] / height for y in [i + 0.5]] for cy, cx in product(dense_cy, dense_cx): anchors += [cx, cy, s_kx, s_ky] return torch.Tensor(anchors).view(-1, 4)
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import json import os import sys import torch class Config(dict): def __getattr__(self, key): if key in self: return self[key] return None def __setattr__(self, key, value): self[key] = value class Base: def __init__(self, model_path, model_category, model_name, meta_file='model_meta.json'): model_root_dir = os.path.join(model_path, model_category, model_name) meta_file_path = os.path.join(model_root_dir, meta_file) with open(meta_file_path, 'r') as f: self.meta_conf = json.load(f) model_root = os.path.dirname(model_path) if model_root not in sys.path: sys.path.append(model_root) self.model_path = model_path self.model_category = model_category self.model_name = model_name self.model_file_path = os.path.join(model_root_dir, self.meta_conf['model_file']) self.model_type = self.meta_conf['model_type'] self.model_info = self.meta_conf['model_info'] self.release_date = self.meta_conf['release_date'] self.input_height = self.meta_conf['input_height'] self.input_width = self.meta_conf['input_width'] self.device = None self.model = None def load(self, device=None): assert self.model is None if device is None: if torch.cuda.is_available(): device = "cuda:%d" % torch.cuda.current_device() else: device = "cpu" self.device = torch.device(device) self.model = torch.load(self.model_file_path, map_location=self.device) self.model.eval()
{ "imports": [ "/xface/model/base.py" ] }
007gzs/xface
refs/heads/master
/xface/face_analysis.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import os import numpy as np from xface.core.image_cropper import crop_image_by_mat from xface.model import FaceAlignment, FaceDetector, FaceRecognition class Face: def __init__(self, *, bbox, det_score, landmark, landmark_106, feature, sim_face_ids): """ :param bbox: 脸部范围 :param landmark: 5关键点位置 :param landmark_106: 106关键点位置 :param det_score: 检测分数 :param feature: 特征 :param sim_face_ids: 相似人脸 """ self.bbox = bbox self.det_score = det_score self.landmark = landmark self.landmark_106 = landmark_106 self.feature = feature self.sim_face_ids = sim_face_ids @classmethod def compute_sim(cls, face1, face2): feature1 = face1.feature if isinstance(face1, Face) else face1 feature2 = face2.feature if isinstance(face2, Face) else face2 return np.dot(feature1, feature2) class FaceAnalysis: def __init__(self, *, model_path=None, with_mask=False, lock=False, load_alignment=True, load_recognition=True): """ :param model_path: 模型路径 :param with_mask: 是否使用口罩模型 :param lock: get_faces是否加锁 :param load_alignment: 是否加载关键点模型 :param load_recognition: 是否加载人脸识别模型 """ if model_path is None: model_path = os.path.join(os.path.dirname(__file__), 'models') mask_flag = '2.0' if with_mask else '1.0' self.face_detector = FaceDetector(model_path, 'face_detection', 'face_detection_' + mask_flag) if load_alignment: self.face_alignment = FaceAlignment(model_path, 'face_alignment', 'face_alignment_' + mask_flag) else: self.face_alignment = None if load_recognition: self.face_recognition = FaceRecognition(model_path, 'face_recognition', 'face_recognition_' + mask_flag) else: self.face_recognition = None self.registered_faces = list() if lock: import threading self.lock = threading.Lock() else: class NoLock: def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass self.lock = NoLock() def register_face(self, face_id, face): """ 注册人脸 :param face_id: 唯一标识 :param face: Face 或 Face.feature """ self.registered_faces.append((face_id, face)) def check_face(self, face, min_sim=0.6, max_count=1): """ :param face: Face :param min_sim: 相似度下限 :param max_count: 返回数量 :return: """ ret = list() for face_id, reg_face in self.registered_faces: sim = Face.compute_sim(face, reg_face) if sim > min_sim: ret.append((face_id, sim)) ret = list(sorted(ret, key=lambda x: -x[1])) if max_count > 0: return ret[:max_count] else: return ret def load(self, device=None): self.face_detector.load(device) if self.face_alignment is not None: self.face_alignment.load(device) if self.face_recognition is not None: self.face_recognition.load(device) def get_faces( self, image, *, img_scaled=1.0, max_num=0, get_landmark_106=True, get_feature=True, min_sim=0.6, match_num=1 ): """ :param image: 图片 :param img_scaled: 图片已缩放比例(返回缩放前坐标) :param max_num: 最大返回人脸数(0为全部) :param get_landmark_106: 是否返回106关键点 :param get_feature: 是否返回人脸识别相关参数 :param min_sim: 人脸识别相似度下限 :param match_num: 人脸识别匹配返回数量 """ with self.lock: dets, landmarks = self.face_detector.detect(image) ret = list() if dets.shape[0] == 0: return ret if 0 < max_num < dets.shape[0]: area = (dets[:, 2] - dets[:, 0]) * (dets[:, 3] - dets[:, 1]) img_center = image.shape[0] // 2, image.shape[1] // 2 offsets = np.vstack([ (dets[:, 0] + dets[:, 2]) / 2 - img_center[1], (dets[:, 1] + dets[:, 3]) / 2 - img_center[0] ]) offset_dist_squared = np.sum(np.power(offsets, 2.0), 0) values = area - offset_dist_squared * 2.0 # some extra weight on the centering bindex = np.argsort(values)[::-1] # some extra weight on the centering bindex = bindex[0:max_num] dets = dets[bindex, :] for i in range(dets.shape[0]): det = dets[i] landmark = landmarks[i] landmark_106 = None feature = None sim_face_ids = None if get_landmark_106 and self.face_alignment is not None: landmark_106 = self.face_alignment.get(image, det) if get_feature and self.face_recognition is not None: cropped_image = crop_image_by_mat(image, landmark.reshape((np.prod(landmark.shape), )).tolist()) feature = self.face_recognition.get(cropped_image) sim_face_ids = self.check_face(feature, min_sim=min_sim, max_count=match_num) ret.append(Face( bbox=(det[:4] / img_scaled).astype(np.int).tolist(), det_score=float(det[4]), landmark=(landmark / img_scaled).astype(np.int).tolist(), landmark_106=None if landmark_106 is None else (landmark_106 / img_scaled).astype(np.int).tolist(), feature=feature, sim_face_ids=sim_face_ids )) return ret
# encoding: utf-8 from __future__ import absolute_import, unicode_literals from .face_alignment import FaceAlignment from .face_detection import FaceDetector from .face_recognition import FaceRecognition __all__ = ['FaceAlignment', 'FaceDetector', 'FaceRecognition']
{ "imports": [ "/xface/model/__init__.py" ] }
00ba/KI
refs/heads/master
/test_tree.py
''' Created on Sep 4, 2016 @author: oobasatoshi ''' from tree import * import unittest class Test(unittest.TestCase): def test_tree(self): self.assertEquals(ki1.view, {'left': 'ki2', 'right': 'ki3', 'name': 'one', 'number': '1'}) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.test_tree'] unittest.main()
''' Created on Sep 4, 2016 @author: oobasatoshi ''' class Tree: def __init__(self, name, number): self.nord = {'name':'', 'number':'', 'left':'', 'right':''} self.nord['name'] = name self.nord['number'] = number self.nord['left'] = '' self.nord['right'] = '' def view(self): print self.nord def add(self): pass def size(self): pass def delete(self): pass def del_root(self): pass def choose_root(self): pass if __name__ == '__main__': ki1 = Tree('one', 1) ki2 = Tree('two', 2) ki3 = Tree('three', 3) ki1.nord['left'] = ki2 ki1.nord['right'] = ki3 ki1.view() ki2.view() ki3.view() ki1.nord['left'].view() ki1.nord['right'].view()
{ "imports": [ "/tree.py" ] }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3