-
Notifications
You must be signed in to change notification settings - Fork 2
/
fuorc
268 lines (217 loc) · 8.15 KB
/
fuorc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# -*- mode: Python; -*-
# vi: ft=python
import os
import json
import time
import threading
from functools import partial
from feeluown.utils import aio
# 自定义配置
# config.THEME = 'macos_dark'
# config.COLLECTIONS_DIR = '~/Dropbox/public/music'
try:
config.dl.ENABLE_V2 = True
config.dl.CORE_LANGUAGE = 'cn'
except:
pass
config.ENABLE_NEW_HOMEPAGE = True
config.bilibili.ENABLE_LIVE_ROOM_AS_VIDEO = False
config.AUDIO_SELECT_POLICY = '>>>'
config.VIDEO_SELECT_POLICY = 'hd>>>'
config.PROVIDERS_STANDBY = ['ytmusic']
config.ENABLE_TRAY = True
config.ENABLE_WEB_SERVER = False
config.NOTIFY_ON_TRACK_CHANGED = False
config.ALLOW_LAN_CONNECT = True
config.PLAYBACK_CROSSFADE = True
config.LOG_TO_FILE = False
config.YTDL_RULES = [{'name': 'match_source',
'pattern': 'ytmusic',
'http_proxy': 'http://127.0.0.1:7890'},]
# This feature is supported at version>=v3.8.12 .
# Besides, if ytmusic plugin is not installed, then
# this config is invalid.
try:
config.ytmusic.HTTP_PROXY='http://127.0.0.1:7890'
except:
pass
# def update_netease_request_headers(*args, **kwargs):
# from fuo_netease import provider
#
# # 海外用户可以给它设置 IP,避免被 block
# provider.api.headers.update({'X-Real-Ip': '...'})
def sync_slack_status(song):
slack_legacy_token = os.getenv('SLACK_TOKEN')
if slack_legacy_token is None or song is None:
return
try:
from slacker import Slacker
except ImportError:
print('WARN: slacker is not installed')
return
slacker = Slacker(slack_legacy_token)
title = song.title_display or 'unknown'
artists_name = song.artists_name_display or 'unknown'
status = f"{title} - {artists_name}"
profile = f'{{"status_text": "正在听:{status}", "status_emoji": ":headphones:"}}'
threading.Thread(target=partial(slacker.users.profile.set, profile=profile)).start()
class FeishuStatusSyncer:
def __init__(self):
self._last_ts = time.time()
def sync(self, metadata):
aio.run_fn(self._sync, metadata)
def _sync(self, metadata):
session_id = os.getenv('FEISHU_SESSION_ID')
note = os.getenv('FEISHU_STATUS_NOTE')
title = metadata.get('title')
interval = time.time() - self._last_ts
if session_id is None:
return
if not title or interval < 10:
print('Sync feishu status too frequently')
return
try:
import requests
except ImportError:
print('WARN: will not sync fesihu-status since requests is not installed')
return
url = 'https://internal-api-lark-api.feishu.cn/passport/users/details/'
headers = {
'user-agent': ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'),
}
cookies = {'session': session_id}
artists = metadata.get('artists', [])
artists_name = ','.join(artists)
description = f'Orz 🎶 {title}'
#if artists_name:
# description += f' - {artists_name}'
#if note:
# description = f'和“{description}”一起打工'
data = {
'description': description,
'descriptionType': 0
}
resp = requests.put(url, data=json.dumps(data), headers=headers, cookies=cookies)
js = json.loads(resp.text)
if js.get('code', 1) != 0:
print('ERROR: Sync feishu status failed', js)
print('Sync feishu status', js)
feishu_status_syncer = FeishuStatusSyncer()
def sync_feishu_status(metadata):
global feishustatussyncer
feishu_status_syncer.sync(metadata)
# when('app.playlist.song_changed', sync_slack_status, use_symbol=True)
when('app.player.metadata_changed', sync_feishu_status, use_symbol=True)
# when('app.initialized', lambda _: print('!!! DEBUG: app initialized'))
# when('app.initialized', update_netease_request_headers)
netease_log_song = None
def netease_log_on_song_changed(song):
global app, netease_log_song
if song is None or song.source != 'netease':
netease_log_song = None
return
netease_log_song = song
threading.Thread(target=partial(netease_log_send_request, song)).start()
def netease_log_on_media_finished(*args):
global netease_log_song
if netease_log_song is None:
return
song = netease_log_song
threading.Thread(
target=partial(netease_log_send_request, song, end=True)).start()
netease_log_song = None
def netease_log_send_request(song, end=False):
provider = app.library.get('netease')
# TODO: provider should provide a interface to check the current user
if provider is None or provider._user is None:
return
url = 'https://music.163.com/weapi/feedback/weblog'
json_ = {
'id': str(song.identifier),
'source': 'album', # TODO: use correct type
'sourceid': str(song.album.identifier),
'type': 'song',
}
if end is True:
sourceid = json_.pop('sourceid')
json_['sourceId'] = sourceid
json_['id'] = int(json_['id'])
json_['download'] = 0
json_['end'] = "ui"
json_['wifi'] = 0
json_['time'] = int(song.duration//1000)
data = {
'logs': json.dumps([{
'action': 'play',
'json': json_
}])
}
payload = provider.api.encrypt_request(data)
result = provider.api.request('POST', url, payload)
print(f'send log:{data} to netease: {result}')
#when('app.player.playlist.song_changed', netease_log_on_song_changed, use_symbol=True)
#when('app.player.media_finished', netease_log_on_media_finished, use_symbol=True)
def apply_kvantum(app):
app.ui.page_view.setStyleSheet("background-color: transparent")
if os.environ.get('QT_STYLE_OVERRIDE'):
when('app.initialized', apply_kvantum, use_symbol=True)
def ask_ai_background(ctx):
global app
from openai import OpenAI, AsyncOpenAI
from functools import partial
from feeluown.utils.aio import run_fn, run_afn
from feeluown.library import ModelType
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox
models = ctx['models']
add_action = ctx['add_action']
song = models[0]
openai_kwargs = dict(
base_url='https://open.bigmodel.cn/api/paas/v4/',
api_key=os.getenv('GLM_API_KEY', '')
)
model = 'glm-4'
# openai_kwargs = dict(
# base_url='https://api.deepseek.com/v1',
# api_key=os.getenv('DEEPSEEK_API_KEY', '')
# )
# model = 'deepseek-chat'
# openai_kwargs = dict(
# base_url='https://api.moonshot.cn/v1',
# api_key=os.getenv('MOONSHOT_API_KEY', '')
# )
# model = 'moonshot-v1-8k'
async def task():
app.show_msg("正在向 AI 提问,这可能需要几秒钟...", timeout=3000)
prompt = ("你是一个专业,严谨的信息检索官,熟知各类流行音乐的创作背景,获奖记录。"
"你也是一个乐评人,懂得从各个角度评价一首歌曲,比如创作背景、轶事、歌词、旋律等")
message = f'你介绍一下 “{song.title}-{song.artists_name} ” 这首歌'
if True or api_key:
client = AsyncOpenAI(**openai_kwargs)
system_msg = {
"role": "system",
"content": prompt,
}
user_msg = {
"role": "user",
"content": message
}
stream = await client.chat.completions.create(
model=model,
messages=[system_msg, user_msg],
temperature = 0.3,
stream=True,
)
box = QMessageBox(parent=app)
box.setAttribute(Qt.WA_DeleteOnClose);
box.setText('')
box.open()
content = ''
async for chunk in stream:
content += chunk.choices[0].delta.content or ''
box.setText(content)
def callback(models):
run_afn(task)
add_action('AI:歌曲创作背景', callback)
when('app.ui.songs_table.about_to_show_menu', ask_ai_background, use_symbol=True)