You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
text/src/create_sample_data.py

84 lines
3.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# create_music_data.py
import os
import django
from django.core.files import File
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'music.settings')
django.setup()
from index.models import Label, Song, Dynamic
def import_local_music():
# 基础路径
base_dir = r'C:\Users\27300\text\src\static'
# 获取现有的音乐文件
song_files_dir = os.path.join(base_dir, 'songFile')
song_img_dir = os.path.join(base_dir, 'songImg')
song_lyric_dir = os.path.join(base_dir, 'songLyric')
# 检查目录是否存在
if not os.path.exists(song_files_dir):
print(f"歌曲文件目录不存在: {song_files_dir}")
return
# 创建默认分类
pop_label, _ = Label.objects.get_or_create(label_name='流行音乐')
# 获取所有音乐文件
music_files = [f for f in os.listdir(song_files_dir) if f.endswith('.mp3')]
print(f"找到 {len(music_files)} 个音乐文件")
for music_file in music_files:
# 从文件名提取歌曲信息(假设文件名为 "歌手 - 歌曲名.mp3"
filename = os.path.splitext(music_file)[0]
if ' - ' in filename:
singer, song_name = filename.split(' - ', 1)
else:
singer = '未知歌手'
song_name = filename
# 检查对应的图片和歌词文件
img_file = f"{os.path.splitext(music_file)[0]}.jpg"
lyric_file = f"{os.path.splitext(music_file)[0]}.txt"
song_img_path = os.path.join(song_img_dir, img_file) if os.path.exists(os.path.join(song_img_dir, img_file)) else 'default.jpg'
song_lyric_path = os.path.join(song_lyric_dir, lyric_file) if os.path.exists(os.path.join(song_lyric_dir, lyric_file)) else '暂无歌词'
# 只保存文件名,不保存完整路径
song_img = os.path.basename(song_img_path) if song_img_path != 'default.jpg' else 'default.jpg'
song_lyric = os.path.basename(song_lyric_path) if song_lyric_path != '暂无歌词' else '暂无歌词'
# 创建或更新歌曲记录
song, created = Song.objects.get_or_create(
song_name=song_name,
defaults={
'song_singer': singer,
'song_time': '04:00', # 默认时长
'song_album': '未知专辑',
'song_languages': '中文',
'song_company': '未知公司',
'song_release': '2023-01-01',
'song_img': song_img,
'song_lyrics': song_lyric,
'song_file': music_file, # 只保存文件名
'label': pop_label
}
)
if created:
# 创建动态数据
Dynamic.objects.create(
song=song,
dynamic_plays=0,
dynamic_search=0,
dynamic_down=0
)
print(f"✅ 导入歌曲: {singer} - {song_name}")
else:
print(f"⏩ 歌曲已存在: {singer} - {song_name}")
if __name__ == '__main__':
import_local_music()
print("🎵 音乐数据导入完成!")