Spaces:
Runtime error
Runtime error
Convert from file
Browse filesFiles changed (3)
- app.py+46-39
- src/convert.py+29
- src/neighbours.py-1
6 unmodified lines7891011121343 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711872 unmodified lines1911921931941951966 unmodified linesimport jsonimport osfrom src.convert import get_embeddings_from_chord_sequencesfrom src.analysis import EmbeddingsAnalysis# Configuration43 unmodified linesresult.append(group_result)return resultdef analyze_chord_sequence(chord_text):"""Analyze a chord sequence from text input"""try:chords = parse_chord_input(chord_text)if not chords:return "Please enter some chords!", "", ""# Get embeddingsembeddings = get_embeddings_from_chord_sequences([chords])# Get scoresscores = ea.get_scores(embeddings, [len(chords)])# Get neighboursneighbours = ea.get_neighbours(embeddings, limit=10)# Format results# Simple originality score displayscore = scores[0]scores_text = f"**Originality Score:** {score:.4f}"# Format neighboursneighbours_text = "**Similar Songs:**\n"if neighbours and len(neighbours) > 0 and len(neighbours[0]) > 0:for i, neighbor in enumerate(neighbours[0][:5], 1): # Show top 5title = neighbor.metadata.get('title', 'Unknown')artist = neighbor.metadata.get('artist', 'Unknown')distance = neighbor.distanceneighbours_text += f"{i}. {title} by {artist} (distance: {distance:.3f})\n"else:neighbours_text += "No similar songs found."return scores_text, neighbours_textexcept Exception as e:return f"Error: {str(e)}", ""def analyze_music_file(audio_file):"""Analyze music file - placeholder for now"""if audio_file is None:return "Please upload a music file!", "", ""# This is a placeholder - you'll need to implement audio processing# For now, we'll return a message about future implementationreturn ("**File uploaded:** " + audio_file.name,"Audio analysis feature coming soon! Currently, this would:\n""1. Extract chords from the audio file\n""2. Convert them to embeddings\n""3. Analyze originality and find similar songs","Please use the 'Text Input' tab for now to analyze chord sequences directly.")# Create Gradio interfacewith gr.Blocks(title="Harmonic Analysis Tool") as app:gr.Markdown("# 🎵 Harmonic Analysis Tool")gr.Markdown("Analyze chord progressions for originality and find similar songs in the database.")72 unmodified linesserver_name="0.0.0.0",server_port=7860,share=False,show_error=True,theme=gr.themes.Soft())6 unmodified lines7891011121343 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512672 unmodified lines1992002012022036 unmodified linesimport jsonimport osfrom src.convert import get_embeddings_from_chord_sequences, get_embedding_from_filepathsfrom src.analysis import EmbeddingsAnalysis# Configuration43 unmodified linesresult.append(group_result)return resultdef _perform_analysis(embeddings, sequence_lengths):"""Private function to perform analysis on embeddings and format results"""# Get scoresscores = ea.get_scores(embeddings, sequence_lengths)# Get neighboursneighbours = ea.get_neighbours(embeddings, limit=10)# Format resultsscore = scores[0]scores_text = f"**Originality Score:** {score:.4f}"# Format neighboursneighbours_text = "**Similar Songs:**\n"if neighbours and len(neighbours) > 0 and len(neighbours[0]) > 0:for i, neighbor in enumerate(neighbours[0][:5], 1): # Show top 5title = neighbor.metadata.get('title', 'Unknown')artist = neighbor.metadata.get('artist', 'Unknown')distance = neighbor.distanceneighbours_text += f"{i}. {title} by {artist} (distance: {distance:.3f})\n"else:neighbours_text += "No similar songs found."return scores_text, neighbours_textdef analyze_chord_sequence(chord_text):"""Analyze a chord sequence from text input"""try:chords = parse_chord_input(chord_text)if not chords:return "Please enter some chords!", ""# Get embeddingsembeddings = get_embeddings_from_chord_sequences([chords])# Perform analysis using shared logicreturn _perform_analysis(embeddings, [len(chords)])except Exception as e:return f"Error: {str(e)}", ""def analyze_music_file(audio_file):"""Analyze music file by extracting chords and computing embeddings"""if audio_file is None:return "Please upload a music file!", "", ""try:# Get embeddings from the audio fileembeddings, chord_lens = get_embedding_from_filepaths([audio_file])# Perform analysis using shared logicscores_text, neighbours_text = _perform_analysis(embeddings, chord_lens)# Add file infofile_info = f"**File analyzed:** {os.path.basename(audio_file)}"return file_info, scores_text, neighbours_textexcept Exception as e:return f"**Error processing file:** {str(e)}", "", ""# Create Gradio interfacewith gr.Blocks(title="Harmonic Analysis Tool", theme=gr.themes.Soft()) as app:gr.Markdown("# 🎵 Harmonic Analysis Tool")gr.Markdown("Analyze chord progressions for originality and find similar songs in the database.")72 unmodified linesserver_name="0.0.0.0",server_port=7860,share=False,show_error=True)
2 unmodified lines34567891015 unmodified lines2627282 unmodified linesimport osimport json_CONSTANT_GAP_SECS = 2_SEQ_EMBED_SPACE = 'ohollo/chord-seq-embed'_client = Client(_SEQ_EMBED_SPACE)15 unmodified linesfor chord_sequence in chord_sequences]return np.array(_call_embedding_service(chords_w_timestamps)['embeddings'])2 unmodified lines3456789101112131415 unmodified lines303132333435363738394041424344454647484950515253545556572 unmodified linesimport osimport jsonfrom chord_extractor.extractors import Chordinofrom chord_extractor import clear_conversion_cache, LabelledChordSequence_CONSTANT_GAP_SECS = 2_SEQ_EMBED_SPACE = 'ohollo/chord-seq-embed'_POST_PROCESS_CHORD_LEN_RATIO = 0.7_client = Client(_SEQ_EMBED_SPACE)15 unmodified linesfor chord_sequence in chord_sequences]return np.array(_call_embedding_service(chords_w_timestamps)['embeddings'])def get_embedding_from_filepaths(file_paths: list[str]) -> tuple[np.ndarray, list[int]]:"""Reads chord sequences from a given filepath and converts them into embeddings.:param file_paths: List of paths to the audio files. Can be anything supported by chord-extractor - .mid, .wav, .mp3, .ogg:return: 2-d numpy array of embeddings per chord sequence."""chords_w_timestamps = []chord_lengths = []chordino = Chordino()for file_path in file_paths:if not os.path.isfile(file_path):raise FileNotFoundError(f"File not found: {file_path}")conversion_file_path = chordino.preprocess(file_path)chords = chordino.extract(conversion_file_path if conversion_file_path else file_path)chords_w_timestamps.append({'label': [chord.chord for chord in chords],'timestamp': [chord.timestamp for chord in chords]})chord_lengths.append(int(len(chords) * _POST_PROCESS_CHORD_LEN_RATIO))return np.array(_call_embedding_service(chords_w_timestamps)['embeddings']), chord_lengths
34 unmodified lines3536373839404134 unmodified linesself._close_threshold = close_thresholddef get(self, embeddings: np.ndarray, limit: int = None) -> list[list[Neighbour]]:# lims, D, I = self._index.range_search(embeddings, self._close_threshold)all_neighbours = []for indices_, distances_ in indices_distances_gen(embeddings, self._close_threshold, self._index):lengths_ = self._lengths[indices_]34 unmodified lines35363738394034 unmodified linesself._close_threshold = close_thresholddef get(self, embeddings: np.ndarray, limit: int = None) -> list[list[Neighbour]]:all_neighbours = []for indices_, distances_ in indices_distances_gen(embeddings, self._close_threshold, self._index):lengths_ = self._lengths[indices_]
app.py+46-39
src/convert.py+29
src/neighbours.py-1