Skip to content
This repository has been archived by the owner on Sep 21, 2022. It is now read-only.

fix Sqlite3Manager problem & prove WyySongOrderer #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions modules/GroupWordCloudGenerator/Sqlite3Manager.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import sqlite3
import os
from pathlib import Path


class Sqlite3Manager:
__instance = None
__first_init: bool = False
path: str = None
__conn = None

def __new__(cls):
Expand All @@ -15,8 +14,7 @@ def __new__(cls):

def __init__(self):
if not self.__first_init:
self.path = os.getcwd()
self.__conn = sqlite3.connect(self.path + './modules/GroupWordCloudGenerator/chatRecord.db')
self.__conn = sqlite3.connect(Path(__file__).parent / "chatRecord.db")
cur = self.__conn.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS `chatrecord` (
Expand Down
6 changes: 2 additions & 4 deletions modules/ImageSender/Sqlite3Manager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sqlite3
import os
from pathlib import Path


keywords_init_sql = [
Expand All @@ -14,7 +14,6 @@
class Sqlite3Manager:
__instance = None
__first_init: bool = False
path: str = None
__conn = None

def __new__(cls):
Expand All @@ -24,8 +23,7 @@ def __new__(cls):

def __init__(self):
if not self.__first_init:
self.path = os.getcwd()
self.__conn = sqlite3.connect(self.path + './modules/ImageSender/imageSenderInfo.db')
self.__conn = sqlite3.connect(Path(__file__).parent / "imageSenderInfo.db")
cur = self.__conn.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS `setting` (
Expand Down
6 changes: 2 additions & 4 deletions modules/KeywordDetection/Sqlite3Manager.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import sqlite3
import os
from pathlib import Path


class Sqlite3Manager:
__instance = None
__first_init: bool = False
path: str = None
__conn = None

def __new__(cls):
Expand All @@ -15,8 +14,7 @@ def __new__(cls):

def __init__(self):
if not self.__first_init:
self.path = os.getcwd()
self.__conn = sqlite3.connect(self.path + './modules/KeywordDetection/keywordDetection.db')
self.__conn = sqlite3.connect(Path(__file__).parent / "keywordDetection.db")
cur = self.__conn.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS `keywords` (
Expand Down
6 changes: 2 additions & 4 deletions modules/KeywordReply/Sqlite3Manager.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import sqlite3
import os
from pathlib import Path


class Sqlite3Manager:
__instance = None
__first_init: bool = False
path: str = None
__conn = None

def __new__(cls):
Expand All @@ -15,8 +14,7 @@ def __new__(cls):

def __init__(self):
if not self.__first_init:
self.path = os.getcwd()
self.__conn = sqlite3.connect(self.path + './modules/KeywordReply/keywordReply.db')
self.__conn = sqlite3.connect(Path(__file__).parent / "keywordReply.db")
cur = self.__conn.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS `keywordReply` (
Expand Down
Binary file removed modules/WyySongOrderer/silk_v3_encoder.exe
Binary file not shown.
70 changes: 5 additions & 65 deletions modules/WyySongOrderer/utils.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import aiofiles
import asyncio
import traceback
import aiohttp
import json
from pydub import AudioSegment
import jpype
from jpype import *

import aiohttp
from graia.application import GraiaMiraiApplication
from graia.application.message.chain import MessageChain
from graia.application.message.elements.internal import Plain
from graiax import silkcoder


async def get_song_ordered(keyword: str, app: GraiaMiraiApplication) -> MessageChain:
Expand All @@ -34,7 +29,8 @@ async def get_song_ordered(keyword: str, app: GraiaMiraiApplication) -> MessageC
data_json = json.loads(data_json)

if data_json["code"] != 200:
return MessageChain.create([Plain(text=f"服务器返回错误:{data_json['message']}")])
return MessageChain.create(
[Plain(text=f"服务器返回错误:{data_json['message']}")])

if data_json["result"]["songCount"] == 0:
return MessageChain.create([Plain(text="没有搜索到呐~换一首歌试试吧!")])
Expand All @@ -47,64 +43,8 @@ async def get_song_ordered(keyword: str, app: GraiaMiraiApplication) -> MessageC
async with session.get(url=music_url) as resp:
music_bytes = await resp.read()

music_bytes = await silk(music_bytes, 'b', '-ss 0 -t 120')
music_bytes = await silkcoder.encode(music_bytes, t=120)

upload_resp = await app.uploadVoice(music_bytes)

return MessageChain.create([upload_resp])


def silk4j_java():
jarPath = "./silk4j-1.0.jar"
jvmPath = jpype.getDefaultJVMPath()
jpype.startJVM(jvmPath, "-ea", f"-Djava.class.path={jarPath}")
audio_utils_class = JClass("io.github.mzdluo123.silk4j.AudioUtils")
util = audio_utils_class()
util.init()
file = java.io.File("./cache.mp3")
silk_file = util.mp3ToSilk(file)
output_file = java.io.File("./cache.slk")
file_input_stream = java.io.FileInputStream(silk_file)
# buffer = jpype.JArray(tp=jpype.JByte)
# while bytes_read := file_input_stream.read(buffer, 0, 1024):
# print(bytes_read)
# output_file.write(buffer, 0, bytes_read)

util.streamToTempFile(file_input_stream, output_file)

output_file.close()
file_input_stream.close()

jpype.shutdownJVM()


async def silk(data, mtype='b', options=''):
try:
cache_files = ['./modules/WyySongOrderer/cache.wav']

if mtype == 'f':
file = data
elif mtype == 'b':
async with aiofiles.open('./modules/WyySongOrderer/music_cache', 'wb') as f:
await f.write(data)
file = './modules/WyySongOrderer/music_cache'
cache_files.append(file)
else:
raise ValueError("Not fit music_type. only 'f' and 'b'")

cmd = [
f'ffmpeg -i "{file}" {options} -af aresample=resampler=soxr -ar 24000 -ac 1 -y -loglevel error "./modules/WyySongOrderer/cache.wav"',
f'"./modules/WyySongOrderer/silk_v3_encoder.exe" "./modules/WyySongOrderer/cache.wav" "./modules/WyySongOrderer/cache.slk" -quiet -tencent'
]

for p in cmd:
shell = await asyncio.create_subprocess_shell(p)
await shell.wait()

async with aiofiles.open(f'./modules/WyySongOrderer/cache.slk', 'rb') as f:
b = await f.read()
return b
except Exception:
traceback.print_exc()

silk4j_java()