class Main(QMainWindow): def __init__(self, parent=None): super().__init__() uic.loadUi('main.ui', self) self.initUI() def initUI(self): self.btn_recommend.setStyleSheet( 'QPushButton {background-color: #A3C1DA}') self.btn_recommend.clicked.connect(self.recommend) self.btn_complain.setStyleSheet( 'QPushButton {background-color: #A3C1DA}') self.btn_complain.clicked.connect(self.complain) self.btn_profil.setStyleSheet( 'QPushButton {background-color: #A3C1DA}') self.btn_profil.clicked.connect(self.profil) self.btn_backToAutentification.setStyleSheet( 'QPushButton {background-color: #A3C1DA}') self.btn_backToAutentification.clicked.connect( self.backToAutentification) def recommend(self): # Переход в рубрику "Рекомендую" self.m1 = Recommend(self) self.m1.show() def complain(self): # Переход в рубрику "Пожаловаться" self.m2 = Complain(self) self.m2.show() def profil(self): # Переход во вкладку "Профиль" self.m3 = Profil(self) self.m3.show() def backToAutentification(self): # Вернуться назад self.close()
def api_recommend(rid): limit = 8 candidates = {} for r in RoomUsers.select(): candidates[str(r.room.room_key)] = {} candidates[str(r.room.room_key)]['ucount'] = r.ucount c = 0 for rc in RoomCommonUsers.select().where(RoomCommonUsers.room1 == int(rid)): candidates[str(rc.room2.room_key)]['common'] = rc.ucount c += 1 if c > 0: rmd = Recommend(str(rid), candidates) result = rmd.get_result() else: r = mongo_db['room'].find_one({'rid': str(rid)}) if r is not None: js = json.loads(api_cate_room(r['cid'], page=1).data) js['data'] = js['data'][:limit] return jsonify(js) else: return jsonify({'code': 1, 'msg': 'invalid request'}) meta = [] for doc in mongo_db['room'].find({'isOnline': True, 'rid': {'$in': result}}).limit(limit): doc.pop('_id') doc.pop('isOnline') doc['roomUrl'] = url_for('live', rid=doc['rid']) doc['cateUrl'] = '/cate/%s' % doc['cid'] meta.append(doc) return jsonify({'code': 0, 'msg': 'success', 'data': meta})
def main(): global conn, config, recommend path = os.path.dirname(__file__) log_filename = os.path.join(path, 'web_log.log') logging.basicConfig(level=logging.INFO, filename=log_filename, filemode='a', format = "%(asctime)s %(levelname)s %(name)s %(message)s") logging.info("############configs##############") conf_path = os.path.join(path, 'config') logging.info('loading conf ' + conf_path) conf = configparser.ConfigParser() conf.read(conf_path) for section in conf.sections(): for item in conf.items(section): logging.info(section + "." + item[0] + "=" + item[1]) logging.info("############configs##############") try: db = os.path.join(path, 'web_log.db') conn = sqlite3.connect(db) createTable() recommend = Recommend('web_log.db') recommend.load_exclude() logging.info("SVM training....") recommend.train() run(host=conf.get('server', 'host'), port=conf.get('server', 'port') , debug=conf.get('server', 'debug')) finally: if conn: conn.close()
def main(): # コマンドライン引数からターゲットユーザを読み込む argvs = sys.argv argc = len(argvs) if argc == 2: target_user = argvs[1] # データセットとinfoファイル名を指定 dataset = os.path.join(DATASET_DIR, "u.data") info_file = os.path.join(DATASET_DIR, "u.info") # レコメンドシステム用にデータを生成 rating_data = os.path.join(DATA_DIR, "movie_table.csv") if not(os.path.isfile(rating_data)): # データセットの前処理を行う ppd = PreprocessingDataset(dataset, info_file) # データセットから「縦:ユーザ、横:映画」の構成で # 各ユーザが評価した、映画の評価値が表になるように # data/movie_table.csvを生成 ppd.preprocessing() # レコメンドシステム用にデータを生成 u_item = os.path.join(DATA_DIR, "u_item.csv") if not(os.path.isfile(u_item)): # 映画名が列挙されているデータを読み込む u_item = os.path.join(DATASET_DIR, "u.item") ppui = PreprocessingUItem(u_item) # データセットをクリーニングして # data/u_item.csvを生成 ppui.preprocessing() # 生成したデータを使ってレコメンドを行う rating_data = os.path.join(DATA_DIR, "movie_table.csv") print("Now target user: %s" % target_user) rc = Recommend(rating_data, info_file, u_item, target_user) # ターゲットに似ているユーザを表示する print("\n========== Similar Users ==========") rc.get_similar_user() # ターゲットにレコメンドを行う print("\n============ Recommend ============") rc.recommend() else: print("Please input target user.\n") print("For example: \n $ python main.py user1")
def results(): g.data = request.json g.data = g.data['recommendation_data'][0] g.books_selected = g.data['books_selected'] g.features_list = g.data['features_list'] g.up_voted = g.data['up_voted'] g.down_voted = g.data['down_voted'] g.books_returned = g.data['books_returned'] g.books_read = g.data['books_read'] g.prev_click = g.data['prev_click'] g.more_click = g.data['more_click'] g.collab_start_point = 0 if g.more_click == 'yes': g.collab_start_point = g.data['collab_returned'] for book in g.books_read: g.books_returned.append(str(book)) g.Recommend = Recommend(user=g.user, db=db, Read=Read, Book=Book, book_data=book_data, ipca_model=ipca_model, dict_vectorizer_fit=dict_vectorizer_fit, collab_start_point=g.collab_start_point) g.recommended_books = g.Recommend.recommend_books(books_selected=g.books_selected, features_list=g.features_list, books_returned=g.books_returned, up_votes=g.up_voted, down_votes=g.down_voted, n_collab_returned=100) rec_data = {"recommendations": g.recommended_books, "collab_returned":g.Recommend.collab_returned} return jsonify(rec_data)
def recommend(self): print() print('<recommend>') uid = int(self.getdata(64)) if not uid: return print("uid: ", uid) recommend = Recommend(uid) recommend.run() print(recommend.items) for i in range(10): data = str(recommend.items[i]) + '\n' self.connection.sendall(data.encode()) print('</recommend>') print()
def test_eng_and_kor(self): mock = Mock(return_value=[ '유선마우스) 3M마우스 사용후기', '제닉스 TITAN GM AIR WIRELESS (화이트) 마우스 사용 후기', '마이크로소프트 스컬프트 마우스 한 달이상 사용후기', '로지텍 G603 무선 마우스 사용후기' ]) term = TermProject() reco = Recommend() term.search('마우스') result_1 = reco.titleList self.assertEqual(result_1[0], mock()[0])
def recommend(self): # Переход в рубрику "Рекомендую" self.m1 = Recommend(self) self.m1.show()
def __init__(self, root): self.root = root self.create() self.recommender = Recommend( "/Users/josephbarbati/Documents/codefiles/Emory/CS378/Final_Project/code/Frequent_Itemsets.txt" )
def add(): view = "" registId = "" form = {} kind = "入力" data = [-2, -1, 0, 1, 2] # GETされた場合 if request.method == 'GET': # TODO: id指定された場合 # 表示処理 return template('add.html', form=form, kind=kind, registId=registId, data=data) # POSTされた場合 if request.method == 'POST': # POST値の取得 form['evaluation'] = request.forms.decode().get('evaluation') form['weight'] = request.forms.decode().get('weight') form['fruity'] = request.forms.decode().get('fruity') form['acidity'] = request.forms.decode().get('acidity') form['spicy'] = request.forms.decode().get('spicy') form['memo'] = request.forms.decode().get('memo') registId = "" # idが指定されている場合 if request.forms.decode().get('id') is not None: registId = request.forms.decode().get('id') # バリデーション処理 errorMsg = [] errorMsg = Utils.validate(data=form) # 表示処理 # 確認画面から戻る場合 if request.forms.get('next') == 'back': return template('add.html', form=form, kind=kind, registId=registId, data=data) if not errorMsg: headers = [ '重み(軽やか - 濃厚)', '果実味(スパイシー - フルーティ)', '酸味(まろやか - シャープ)', '辛み(甘い - 辛い)', 'メモ' ] temp_df = Recommend(base_df, wine=0, weight=form['weight'], fruity=form['fruity'], acidity=form['acidity'], spicy=form['spicy']) df = search_info(temp_df, wine_df) return template('confirm.html', form=form, headers=headers, df=df, registId=registId) else: return template('add.html', error=errorMsg, kind=kind, form=form, registId=registId, data=data)
else: if len(games) < i + 1: games.append([]) user_id = d[0] dct[d[1]] = d[4] if d[4] == "1": games[i].append(d[1]) # Correctly recommended games / all recommended games avg_prec = 0.0 # Correctly recommended games / all games that should have been recommended avg_recall = 0.0 j = 0 for i in range(len(games) - 1): if len(games[i]) < 2: continue r = Recommend("Frequent_Itemsets.txt") r.set_user_games(games[i]) recommended = r.recommend() # Caluclate Precision and recall. all_rec = len(recommended) should_rec = 0 correct = 0 for key in final_dict[i]: game = key.split('"')[1] if final_dict[i][key] == "0": should_rec += 1 if game in recommended: correct += 1 if should_rec == 0 or all_rec == 0: continue prec = float(float(correct) / float(all_rec))
color = '#303030' strings.append('<table><tr style="border-bottom: 1px solid #666;"><td width="170px";>'+\ '<img src="'+str(row[1])+'" style="opacity:'+opacity+';""></td>') strings[-1] += '<td><h2><a href="/document/'+str(uid)+'/'+str(did)+\ '" style="color:'+color+';">' + str(row[2]) + '</a></h2>\n' strings[ -1] += '<p style="color:#606060; font-size:15"><span style="color:#A0A0A0">' strings[-1] += parser.parse(str( row[0])).strftime('%d/%m/%Y') + '</span>' if str(row[3]) != '': strings[-1] += ' - ' + str(row[3]) strings[-1] += '</p></td></tr></table>\n' #strings[-1] += '\n<hr class="dots"/>\n' return ''.join(strings) if __name__ == '__main__': with open('../TextMining/ac.loc', 'rb') as f: ac = load(f) root = Home(ac) root.topic = Topic(ac) root.document = Document(ac) root.tag = Tag(ac) root.recommend = Recommend(ac) root.search = Search(ac) root.script = Script() #cherrypy.server.socket_host = '192.168.1.95' #cherrypy.engine.start() cherrypy.quickstart(root)
def main(): conf.init_cnf() order = Order() sim = Sim() conn = MySQLdb.connect(host=mysql_cnf['host'], port=int(mysql_cnf['port']), user=mysql_cnf['user'], passwd=mysql_cnf['passwd'], db=mysql_cnf['db'], connect_timeout=3, local_infile=1) mysql_read_order(order, conn) mysql_read_sim(sim, conn) pool = redis.ConnectionPool(host='192.168.9.36', port=6379, db=0, encoding='utf8') r = redis.Redis(connection_pool=pool) recommend = Recommend(order=order, sim=sim) recommend.set_rec(dict()) recommend.set_rec_by_sim_user(size=20) users = recommend.get_rec().keys() for u in users: redis_write_rec('user:'******':sim_user', recommend.get_user_rec(u), r) recommend.set_rec(dict()) recommend.set_rec_by_sim_item(size=20) users = recommend.get_rec().keys() for u in users: redis_write_rec('user:'******':sim_item', recommend.get_user_rec(u), r)
import os, sys import json import requests from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse cur_dir = os.path.dirname( os.path.abspath(__file__)) or os.getcwd() sys.path.append(cur_dir + '/../../') sessionID = "1" history = "" from recommend import Recommend rs = Recommend() ## receive the post input data and process. @csrf_exempt def analyze(request): ctx ={} if request.method=="POST": try: ori = json.loads(request.body) except: HttpResponse("json格式错误") try: ctx['uid'] = uid = ori['uid'] ctx['input'] = content = ori['user_say'] ctx['flag'] = flag = ori['flag'] except: HttpResponse("数据格式错误") # history = request.POST['answer'].strip()
def server_recommend(): global recommend now = datetime.fromtimestamp(time.time()) ip = request.environ.get('REMOTE_ADDR') ip_num = Recommend.ip2value(ip) return recommend.predict([[now.month, now.day, now.weekday(), now.hour, ip_num]])