-
Notifications
You must be signed in to change notification settings - Fork 595
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
8 changed files
with
231 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import uuid | ||
import json | ||
|
||
from .models import BriefSongModel, ModelState | ||
|
||
|
||
class AnalyzeError(Exception): | ||
pass | ||
|
||
|
||
def analyze_text(text): | ||
def json_fn(each): | ||
try: | ||
return each['title'], each['artists_name'] | ||
except KeyError: | ||
return None | ||
|
||
def line_fn(line): | ||
parts = line.split('|') | ||
if len(parts) == 2 and parts[0]: # title should not be empty | ||
return (parts[0], parts[1]) | ||
return None | ||
|
||
try: | ||
data = json.loads(text) | ||
except json.JSONDecodeError: | ||
lines = text.strip().split('\n') | ||
if lines: | ||
first_line = lines[0].strip() | ||
if first_line in ('---', '==='): | ||
parse_each_fn = line_fn | ||
items = [each.strip() for each in lines[1:] if each.strip()] | ||
elif first_line == '```json': | ||
try: | ||
items = json.loads(text[7:-3]) | ||
except json.JSONDecodeError: | ||
raise AnalyzeError('invalid JSON content inside code block') | ||
parse_each_fn = json_fn | ||
else: | ||
raise AnalyzeError('invalid JSON content') | ||
else: | ||
if not isinstance(data, list): | ||
# should be like [{"title": "xxx", "artists_name": "yyy"}] | ||
raise AnalyzeError('content has invalid format') | ||
parse_each_fn = json_fn | ||
items = data | ||
|
||
err_count = 0 | ||
songs = [] | ||
for each in items: | ||
result = parse_each_fn(each) | ||
if result is not None: | ||
title, artists_name = result | ||
song = BriefSongModel( | ||
source='dummy', | ||
identifier=str(uuid.uuid4()), | ||
title=title, | ||
artists_name=artists_name, | ||
state=ModelState.not_exists, | ||
) | ||
songs.append(song) | ||
else: | ||
err_count += 1 | ||
return songs, err_count |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import logging | ||
from typing import TYPE_CHECKING | ||
|
||
from feeluown.library import BriefSongModel, reverse | ||
from feeluown.library.text2song import analyze_text, AnalyzeError | ||
from feeluown.utils.utils import DedupList | ||
|
||
try: | ||
from openai import OpenAI | ||
except ImportError: | ||
AI_RADIO_SUPPORTED = False | ||
else: | ||
AI_RADIO_SUPPORTED = True | ||
|
||
if TYPE_CHECKING: | ||
from feeluown.app import App | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def song2line(song: BriefSongModel): | ||
line = reverse(song, as_line=True) | ||
parts = line.split('#', 1) | ||
if len(parts) >= 2: | ||
return parts[1] | ||
return None | ||
|
||
|
||
class AIRadio: | ||
def __init__(self, app: 'App'): | ||
self._app = app | ||
|
||
self._messages = [] | ||
self._unliked_songs = DedupList() | ||
self._app.playlist.songs_removed.connect(self._on_songs_removed, weak=True) | ||
|
||
self._messages.append({"role": "system", | ||
"content": self._app.config.AI_RADIO_PROMPT}) | ||
|
||
def fetch_songs_func(self, _): | ||
client = OpenAI( | ||
api_key=self._app.config.OPENAI_API_KEY, | ||
base_url=self._app.config.OPENAI_API_BASEURL, | ||
) | ||
msg_lines = [] | ||
for song in self._app.playlist.list(): | ||
if self._app.playlist.is_bad(song): | ||
continue | ||
line = song2line(song) | ||
if line is not None: | ||
msg_lines.append(line) | ||
msg = '\n'.join(msg_lines) | ||
# umsg_lines = [] | ||
# for song in self._unliked_songs[-10:]: | ||
# line = song2line(song) | ||
# if line is not None: | ||
# umsg_lines.append(line) | ||
# umsg = '\n'.join(umsg_lines) if umsg_lines else '暂时没有不喜欢的歌曲' | ||
self._messages.append({ | ||
"role": "user", | ||
"content": ( | ||
f"当前播放列表内容如下:\n{msg}") | ||
}) | ||
response = client.chat.completions.create( | ||
model=self._app.config.OPENAI_MODEL, | ||
messages=self._messages, | ||
) | ||
msg = response.choices[0].message | ||
self._messages.append(msg) | ||
for _msg in self._messages[-2:]: | ||
logger.info(f"AI radio, message: {dict(_msg)['content']}") | ||
try: | ||
songs, err_count = analyze_text(str(msg.content)) | ||
except AnalyzeError: | ||
logger.exception('Analyze AI response failed') | ||
return [] | ||
logger.info(f'AI recommend {len(songs)} songs, err_count={err_count}') | ||
return songs | ||
|
||
def _on_songs_removed(self, index, count): | ||
songs = self._app.playlist[index: index + count] | ||
self._unliked_songs.extend(songs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters