CoolFace
Apppublic

NhanNguyen1309/audio-separation-api

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
main.cpython-310.pyc103 linesDownload Raw Back to __pycache__
1o

2x[j%9�@s"ddlmZddlZddlmZddlmZddlmZm	Z	m3Z4mZmZm
Z
ddlmZddlmZddlmZdd	lmZdd5lmZddlmZddlmZdd
lmZmZddlm Z ddl!m"Z"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAddlBmCZCddlDmEZEmFZFmGZGmHZHmIZIhd�ZJdZKd�dd�ZLed�dd ��ZMe	d!d"eMd#�ZNeN�Oe"e#�eNjPee jQd$gd%�d&gd'�eNjRd(e7d)�d�d+d,��ZSd�d0d1�ZTd�d5d6�ZUd�d:d;�ZVd�d?d@�ZWd�dDdE�ZXd�dHdI�ZYd�dMdN�ZZd�dRdS�Z[d�dWdX�Z\d�d[d\�Z]d�dbdc�Z^eNj_dde8d)�e6de�ede�fd�dldm��Z`eNj_dne4d)�e7de�fd�dpdq��ZaeNjRdre5d)�d�dtdu��ZbeN�cdr�d�dwdx��ZdeNjRdye9d)�d�dzd{��ZeeN�fd|�d�d�d���ZgeN�Rd��d�d�d���ZheN�cdy�d�d�d���ZidS)��)�annotationsN)�asynccontextmanager)�Path)�BackgroundTasks�FastAPI�File�Form�8UploadFile�	WebSocket)�CORSMiddleware)�FileResponse)�WebSocketDisconnect)�chord_registry)�ensure_chord_duration)�check_chordino_available)�run_chord_detection_job)�cleanup_expired_chord_jobs�cleanup_expired_jobs)�settings)�ApiError�api_error_handler)�registry)�BpmCandidateRecord�ChordJobRecord�ChordSegmentRecord�	JobRecord�KeyCandidateRecord�KeyDetectionResultRecord�KeyScoreComponentsRecord�SectionKeyResultRecord�SnapConfigRecord�VisualGridRecord�VisualGridCellRecord)�BpmCandidateResponse�ChordJobCreateResponse�ChordJobStatusResponse�ChordSegmentResponse�HealthResponse�JobCreateResponse�JobStatusResponse�TimeSignatureResponse�KeyCandidateResponse�KeyDetectionResultResponse�KeyScoreComponentsResponse�SectionKeyResultResponse�SnapConfigResponse�VisualGridResponse�VisualGridCellResponse)�run_separation_job)�ensure_file_size�ensure_supported_extension�ensure_supported_mime_type�ensure_supported_stem_mode�ensure_duration>�	completed�failedZexpiredg>@�jobr�returnr)cCsF|jdkrd|j�d�nd}t|j|j|j|j|j|j|j|j|d�	S)Nr8z9/api/jobs/z	/download)	�id�status�	stem_mode�progress�stage�10created_at�11updated_at�error�download_url)	r=r<r)r>r?r@rArBrC)r:rD�rE�KD:\workspace\nextjs\music_toolkit_projects\audio-separation-api\app\main.py�build_job_status_response@s�rG�_rcCs8�tjjddd�tjjddd�t�t�dVdS)NT)�parents�exist_ok)rZ	jobs_root�mkdirZchord_jobs_rootrr)rHrErErF�lifespanOs�12rLzAI Audio Stem Separation APIz0.1.0)�title�versionrLF)�GET�POST�DELETE�*)Z
allow_originsZallow_credentialsZ
allow_methodsZ
allow_headersz/health)�response_modelr'cCs t�}tdtj|j|j|jd�S)N�ok)r=�demucs_model�chord_detection_available�chord_engine�13chord_host)rr'rrUrVrWrX)�chordino_statusrErErF�healthgs�rZ�segmentrr&cCst|j|j|j|jd�S)N)�startSec�endSec�chord�14confidence)r&�	start_sec�end_secr^r_)r[rErErF�build_chord_segment_responsess�rb�	candidaterr#cCst|j|j|jd�S)N)�bpm�score�source)r#rdrerf�rcrErErF�build_bpm_candidate_response|srh�cellr"r1c	Cs$t|j|j|j|j|j|j|jd�S)N)�indexZvisualBarIndexZ	cellInBarr\r]Z15isBarStartZ	beatIndex)r1rjZvisual_bar_indexZcell_in_barr`raZis_bar_startZ16beat_index)rirErErF�build_visual_grid_cell_response�s�rk�gridr!r0cCst|jdd�|jD�d�S)NcS�g|]}t|��qSrE)rk)�.0rirErErF�17<listcomp>��z.build_visual_grid_response.<locals>.<listcomp>)ZvisualCellsPerBar�cells)r0Zvisual_cells_per_barrq)rlrErErF�build_visual_grid_response�s�rr�18componentsrr-c19CsNtt|jd�t|jd�t|jd�t|jd�t|jd�t|jd�t|jd�d�S)N�)ZchromaScoreZ
chordFitScoreZtonicDurationScoreZfirstLastScoreZcadenceScoreZ
bassRootScoreZsectionVoteScore)	r-�roundZchroma_scoreZchord_fit_scoreZtonic_duration_scoreZfirst_last_scoreZ
cadence_scoreZbass_root_scoreZsection_vote_score)rsrErErF�#build_key_score_components_response�s20212223242526�rvrr+cCs t|j|j|j|jt|j�d�S)N)�key�tonic�scalerers)r+rwrxryrervrsrgrErErF�build_key_candidate_response�s�rz�sectionrr.cCst|j|j|j|j|jd�S)N)r\r]rwryr_)r.r`rarwryr_)r{rErErF�build_section_key_response�s�r|�resultrr,c27CsFt|j|j|j|j|jdd�|jD�|jrdd�|jD�nd|jd�S)NcSrmrE)rz�rnrcrErErFro�rpz0build_key_detection_response.<locals>.<listcomp>cSrmrE)r|)rnr{rErErFro�rp)rwrxryr_�method�28candidatesZsectionKeys�warnings)	r,rwrxryr_rr�Zsection_keysr�)r}rErErF�build_key_detection_response�s�r��configr r/cCs t|j|j|j|j|j|jd�S)N)ZchordSnapToleranceSecZdownbeatSnapToleranceSecZforwardDownbeatToleranceSecZbackwardDownbeatToleranceSecZvisualCellSnapToleranceSecZdownbeatSnapEnabled)r/Zchord_snap_tolerance_secZdownbeat_snap_tolerance_secZforward_downbeat_tolerance_secZbackward_downbeat_tolerance_secZvisual_cell_snap_tolerance_secZdownbeat_snap_enabled)r�rErErF�build_snap_config_response�s�r�rr%cCs�|j}td!id|j�d|j�d|j�d|j�d|j�d|j�d|jr*dd	�|jD�nd�d29|r2|j	nd�d|r:|j30nd�d|rGd
d	�|jD�nd�d|rO|jnd�d|rW|j
nd�d|r_|jnd�d|rnt|jj|jjd�nd�d|rv|jnd�d|r�t|j�nd�d|r�|jnd�d|r�|jnd�d|r�|jr�dd	�|jD�nd�d|r�|jnd�d|r�|jnd�d|r�|jnd�d|r�|jr�t|j�nd�d|r�|jr�t|j�nd�d|r�|j nd�d|j!�d |j"��S�d|j!�d |j"��S)"Nr<r=r?r@rArBZchordscSrmrE�rb�rnr[rErErFro�rpz3build_chord_job_status_response.<locals>.<listcomp>rdZ
bpmConfidenceZrawBpmCandidatescSrmrE)rhr~rErErFro�rp�beats�	downbeatsZbarStartOffsetSecZ
timeSignature)�	numerator�denominatorZbeatsPerBarZ31visualGridZchordSourceZchordAudioSourceZkeyAnalysisChordscSrmrEr�r�rErErFro�rpZkeyAudioSourceZkeyDetectionSourceZ32beatSourceZ33snapConfigZoriginalKeyr�Z	errorCoderCrE)#�analysisr%r<r=r?r@rArBr}rdZbpm_confidenceZraw_bpm_candidatesr�r�Zbar_start_offset_secr*Ztime_signaturer�r�Z
beats_per_barrrZvisual_gridZchord_sourceZchord_audio_sourceZkey_analysis_chordsZkey_audio_sourceZkey_detection_sourceZbeat_sourceZsnap_configr�Zoriginal_keyr�r�Z34error_coderC)r:r�rErErF�build_chord_job_status_response�s�����������	��35������
�������������������������������r��uploadr	�destinationr�intc�sn�d}|�d��%}	|�d�IdH}|sn|t|�7}t|�|�|�q36Wd�|S1s0wY|S)Nr�wbTi)�open�read�lenr3�write)r�r��total�output�chunkrErErF�save_upload_with_limit�s �37�38�39�40r�z	/api/jobs.�background_tasksr�filer>�strr(c41�s|�|jstdddd��t|j�t|j�t|�}tj||jd�}td|j	�d|�d|j��d	d42�zvz.tj43|j	ddd
d�t||j�IdHt
|j�tj44|j	dddd�td|j	��d	d45�Wn>tyytd|j	��d	d46�t�|j	��ty�}ztd|j	�d|��d	d47�t�|j	�tdddd�|�d}~wwW|��IdHn|��IdHw|�t|j	�t|j	d�S)N�unsupported_file_type�A file name is required.���code�message�status_code)r>�input_filenamez[jobs] create job=z stem_mode=z48 filename=T)�flush�49processing�50�51validating�r=r?r@�queued�z[jobs] queued job=z[jobs] rejected job=z[jobs] invalid_audio job=z error=Z
invalid_audioz*The uploaded audio could not be processed.��job_id)�filenamerr4r5�content_typer6r�52create_job�printr<�53update_jobr��54input_pathr7�55delete_job�	Exception�close�add_taskr2r()r�r�r>Zsupported_moder:�excrErErFr�s8�5657"58��� 59r�z/api/chords/jobsr$c60�s0�|jstdddd��t|j�t|j�t�}|js%t|jp dddd��tj	|jd�}zVz%tj61|jd	d62dd�t||j
�IdHt|j
�}tj63|jd
dd
|d�Wn'ty`t�|j��tyy}zt�|j�tdddd�|�d}~wwW|��IdHn|��IdHw|�t|j�t|jd�S)Nr�r�r�r�Zchordino_unavailablez8Chordino chord detection is unavailable on this backend.i�)r�r�r�r�r�r�r�)r=r?r@Zduration_secZchord_detection_failedz;The uploaded audio could not be queued for chord detection.)Zchord_job_id)r�rr4r5r�rrVrCrr�r�r<r�r�rr�r�r�r�rr$)r�r�rYr:�durationr�rErErF�create_chord_job$s<�6465�66��� r�z/api/chords/jobs/{job_id}r�cC�t�|�}t|�S�N)r�get_jobr��r�r:rErErF�
get_chord_jobJ�67r��dict[str, bool]cC�t�|�ddiS�N�deletedT)rr�r�rErErF�delete_chord_jobPr�r�z/api/jobs/{job_id}cCr�r�)rr�rGr�rErErFr�Vr�r�z/ws/jobs/{job_id}�	websocketr68�Nonec69�s70�zt�|�}Wnty&}z|jd|jd�IdHWYd}~dSd}~ww|��IdHz/	|�t|�jdd��IdH|j	t71vrO|jdd�IdHWdSt�tj
|j|jt�IdH}q0ty{}z|jd|jd�IdHWYd}~dSd}~wty�YdSw)Ni�)r��reasonT�json)�modei�)r�)rr�rr�r��accept�	send_jsonrG�72model_dumpr=�TERMINAL_JOB_STATUSES�asyncio�	to_threadZwait_for_updater<rB�WEBSOCKET_WAIT_TIMEOUT_SECONDSr
)r�r�r:r�rErErF�73stream_job\s8���7475��
$��r�z/api/jobs/{job_id}/downloadrcCsRt�|�}|jdkrtdddd��|j��stdddd��t|jd	|j�d76�d�S)Nr8Z
job_not_readyz"The job is not ready for download.i�r�Zdownload_missingz(The download file is missing or expired.i�zapplication/zipz.zip)�path�77media_typer�)rr�r=r�zip_path�existsrr<r�rErErF�download_jobzs78798081�r�cCr�r�)rr�r�rErErFr��r�r�)r:rr;r))rHr)r;r')r[rr;r&)rcrr;r#)rir"r;r1)rlr!r;r0)rsrr;r-)rcrr;r+)r{rr;r.)r}rr;r,)r�r r;r/)r:rr;r%)r�r	r�rr;r�)r�rr�r	r>r�r;r()r�rr�r	r;r$)r�r�r;r%)r�r�r;r�)r�r�r;r))r�r�r�r82r;r�)r�r�r;r)j�83__future__rr��84contextlibr�pathlibr�fastapirrrrr	r85Zfastapi.middleware.corsr�fastapi.responsesr�starlette.websocketsr
Zapp.chord_jobsrZapp.chord_validationrZapp.chordinorZ86app.chordsrZapp.cleanuprrZ87app.configrZ88app.errorsrrZapp.jobsrZ89app.modelsrrrrrrrrr r!r"Zapp.schemasr#r$r%r&r'r(r)r*r+r,r-r.r/r0r1Zapp.separationr2Zapp.validationr3r4r5r6r7r�r�rGrL�app�add_exception_handler�add_middlewareZcors_origins�getrZrbrhrkrrrvrzr|r�r�r�r��postr�r�r��deleter�r�r�r�r�r�rErErErF�<module>s� 4D
	90�
9192	9394959697 98 99 100 101
102103%�#�%