Commit f5be74e0 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Fix requirements, add src.services and src.core.config package modules for CI

parent 53b953c2
Pipeline #970 failed with stages
in 5 minutes and 47 seconds
...@@ -14,3 +14,5 @@ sqlalchemy>=2.0.0 ...@@ -14,3 +14,5 @@ sqlalchemy>=2.0.0
httpx>=0.27.0 httpx>=0.27.0
python-multipart>=0.0.9 python-multipart>=0.0.9
pytest>=8.0.0 pytest>=8.0.0
pyrogram>=2.0.106
tgcrypto>=1.2.5
import os
import logging
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
LALAL_API_KEY = os.getenv("LALAL_API_KEY")
# Setup centralized logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger("StaxBot")
# src.services package
import os
import aiohttp
from pydub import AudioSegment
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, USLT, TIT2, TPE1, TALB, TDRC, TCON, TRCK, error
from src.core.config import logger
async def download_image(url: str) -> bytes:
if not url: return None
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200: return await response.read()
return None
async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
"""Converts audio to MP3 and applies all ID3 tags. Returns the path to the tagged MP3."""
# 1. Convert to MP3 (or skip if already MP3)
if raw_file_path.lower().endswith('.mp3'):
mp3_file_path = f"{raw_file_path}_tagged.mp3"
import shutil
shutil.copyfile(raw_file_path, mp3_file_path)
else:
mp3_file_path = f"{raw_file_path}.mp3"
audio = AudioSegment.from_file(raw_file_path)
audio.export(mp3_file_path, format="mp3", bitrate="192k")
# 2. Add ID3 Tags
mp3 = MP3(mp3_file_path, ID3=ID3)
try: mp3.add_tags()
except error: pass
title, artist = candidate.get('title', 'Unknown'), candidate.get('artist', 'Unknown')
album, year = candidate.get('album', ''), candidate.get('year', '')
genre, track_num = candidate.get('genre', ''), candidate.get('track_number', '')
lyrics, coverart_url = candidate.get('lyrics'), candidate.get('coverart')
mp3.tags.add(TIT2(encoding=3, text=title))
mp3.tags.add(TPE1(encoding=3, text=artist))
if album: mp3.tags.add(TALB(encoding=3, text=album))
if year: mp3.tags.add(TDRC(encoding=3, text=year))
if genre: mp3.tags.add(TCON(encoding=3, text=genre))
if track_num: mp3.tags.add(TRCK(encoding=3, text=track_num))
if lyrics:
mp3.tags.add(USLT(encoding=3, lang='eng', desc=u'', text=lyrics))
if coverart_url:
image_bytes = await download_image(coverart_url)
if image_bytes:
mp3.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=image_bytes))
mp3.save(v2_version=3)
# 3. Rename file
safe_title = "".join([c for c in title if c.isalnum() or c==' ']).rstrip()
final_filename = f"{safe_title}.mp3" if safe_title else "Unknown Track.mp3"
os.rename(mp3_file_path, final_filename)
return final_filename
import asyncio
import re
import acoustid
import musicbrainzngs
import syncedlyrics
from shazamio import Shazam
from src.core.config import logger, ACOUSTID_API_KEY, GEMINI_API_KEY
import google.generativeai as genai
import json
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com")
async def identify_audio(file_path: str) -> list:
"""Uses Shazamio and AcoustID to identify the audio file. Returns a list of candidates."""
candidates = []
# 1. Shazamio
try:
shazam = Shazam()
out = await shazam.recognize(file_path)
if 'track' in out:
t = out['track']
title = t.get('title', 'Unknown')
artist = t.get('subtitle', 'Unknown')
coverart_url = t.get('images', {}).get('coverart')
album, year, genre = "Unknown Album", "Unknown Year", "Unknown Genre"
for section in t.get('sections', []):
if section.get('type') == 'SONG':
for meta in section.get('metadata', []):
if meta.get('title') == 'Album': album = meta.get('text')
if meta.get('title') == 'Released': year = meta.get('text')
if meta.get('title') == 'Genre': genre = meta.get('text')
lyrics = ""
for section in t.get('sections', []):
if section.get('type') == 'LYRICS':
l_lines = section.get('text', [])
lyrics = "\n".join(l_lines) if isinstance(l_lines, list) else l_lines
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': '1/1', 'source': 'Shazam', 'coverart': coverart_url, 'lyrics': lyrics
})
except Exception as e:
logger.error(f"Shazam error: {e}")
# 2. AcoustID & MusicBrainz
try:
results = await asyncio.to_thread(acoustid.match, ACOUSTID_API_KEY, file_path)
for score, recording_id, title, artist in results:
if score > 0.4:
if not any(c['title'].lower() == title.lower() and c['artist'].lower() == artist.lower() for c in candidates):
album, year, genre, track_number = "Unknown Album", "Unknown Year", "Unknown Genre", "1/1"
try:
mb_data = await asyncio.to_thread(musicbrainzngs.get_recording_by_id, recording_id, includes=["releases"])
rec = mb_data.get('recording', {})
releases = rec.get('release-list', [])
if releases:
rel = releases[0]
album = rel.get('title', album)
year = rel.get('date', year)[:4] if rel.get('date') else year
track_number = f"{rel.get('medium-list', [{}])[0].get('track-list', [{}])[0].get('number', '1')}/{rel.get('medium-list', [{}])[0].get('track-count', '1')}"
except: pass
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': track_number, 'source': f'AcoustID ({int(score*100)}%)', 'coverart': None, 'lyrics': None
})
if len(candidates) >= 4: break
except Exception as e:
logger.error(f"AcoustID error: {e}")
return candidates
async def identify_with_gemini(file_path: str, lang_pref: str) -> dict:
if not GEMINI_API_KEY:
raise Exception("GEMINI_API_KEY not configured.")
model = genai.GenerativeModel('gemini-2.5-flash', generation_config={"response_mime_type": "application/json"})
script_instruction = "Use standard Persian (Farsi) script for the Title and Artist." if lang_pref == "native" else "Use Finglish/English characters (transliterated) for the Title and Artist."
prompt = f"""
You are an expert musicologist specializing in global and Persian music.
Listen to this audio track carefully.
{script_instruction}
Return a JSON object strictly following this schema:
{{
"scratchpad": str (First, transcribe a few prominent lines of the lyrics you hear, and think about who the singer might be based on voice and style. Use this to deduce the song.),
"title": str,
"artist": str,
"album": str,
"year": str,
"genre": str,
"lyrics": str (Write out the full lyrics of the song in Persian script, if applicable)
}}
If you are absolutely unable to identify it even after analyzing the lyrics and voice, return 'Unknown' for fields.
"""
try:
with open(file_path, "rb") as f:
audio_data = f.read()
audio_part = {
"mime_type": "audio/mp3",
"data": audio_data
}
response = await asyncio.to_thread(model.generate_content, [audio_part, prompt])
data = json.loads(response.text)
return {
'title': data.get('title', 'Unknown'),
'artist': data.get('artist', 'Unknown'),
'album': data.get('album', 'Unknown Album'),
'year': data.get('year', 'Unknown Year'),
'genre': data.get('genre', 'Unknown Genre'),
'track_number': '1/1',
'source': 'Gemini AI',
'coverart': None,
'lyrics': data.get('lyrics', '')
}
except Exception as e:
logger.error(f"Gemini identification failed: {e}")
return None
async def fetch_lyrics(title: str, artist: str) -> str:
"""Fetches lyrics using syncedlyrics and strips timestamps."""
if title == 'Unknown Title': return None
try:
lrc = await asyncio.to_thread(syncedlyrics.search, f"{title} {artist}")
if lrc:
clean_lines = [l.strip() for l in lrc.splitlines() if l.strip()]
clean_lines = [re.sub(r'\[\d+:\d+(:\d+)?(\.\d+)?\]', '', l) for l in clean_lines]
clean_lines = [re.sub(r'\[[a-zA-Z]+:.*?\]', '', l) for l in clean_lines]
return "\n".join([l for l in clean_lines if l])
except Exception as e:
logger.error(f"Lyrics fallback error: {e}")
return None
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment