Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,13 +7,13 @@ import zlib
|
|
| 7 |
import base64
|
| 8 |
import statistics
|
| 9 |
import traceback
|
| 10 |
-
import
|
|
|
|
| 11 |
from bs4 import BeautifulSoup
|
| 12 |
from midiutil import MIDIFile
|
| 13 |
|
| 14 |
app = FastAPI()
|
| 15 |
|
| 16 |
-
# Configuration Web
|
| 17 |
app.add_middleware(
|
| 18 |
CORSMiddleware,
|
| 19 |
allow_origins=["*"],
|
|
@@ -27,27 +27,34 @@ BRAIN_FILE = "solfa_brain.pkl"
|
|
| 27 |
TEMPO = 100
|
| 28 |
VELOCITY = 100
|
| 29 |
|
| 30 |
-
# ---
|
| 31 |
class MasterEngine:
|
| 32 |
def __init__(self):
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
with open(BRAIN_FILE, "rb") as f:
|
| 36 |
self.model = pickle.load(f)
|
| 37 |
-
print("✅ Cerveau chargé !")
|
| 38 |
except Exception as e:
|
| 39 |
-
print(f"⚠️
|
|
|
|
|
|
|
| 40 |
self.model = None
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
# Mapping Solfège Chromatique
|
| 45 |
self.chromatic_map = {
|
| 46 |
'd': 0, 'di': 1, 'de': 11, 'r': 2, 'ri': 3, 'ra': 1, 'm': 4, 'ma': 3,
|
| 47 |
'f': 5, 'fi': 6, 's': 7, 'si': 8, 'se': 6, 'l': 9, 'li': 10, 'la': 8, 't': 11, 'ta': 10
|
| 48 |
}
|
| 49 |
|
| 50 |
-
# Tonalités
|
| 51 |
self.key_signatures = {
|
| 52 |
'C': 60, 'D': 62, 'E': 64, 'F': 65, 'G': 67, 'A': 69, 'B': 71,
|
| 53 |
'CB': 59, 'DB': 61, 'EB': 63, 'GB': 66, 'AB': 68, 'BB': 70,
|
|
@@ -66,21 +73,28 @@ class MasterEngine:
|
|
| 66 |
return [notes/length, seps/length, mods/length, bad, density]
|
| 67 |
|
| 68 |
def is_music_ai(self, text):
|
| 69 |
-
"""
|
| 70 |
if not self.model: return False
|
| 71 |
-
if "dia" in text.lower() and len(text) < 20: return False
|
| 72 |
-
feats = self.extract_features(text)
|
| 73 |
try:
|
|
|
|
| 74 |
return self.model.predict([feats])[0] == 1
|
| 75 |
except:
|
| 76 |
return False
|
| 77 |
|
| 78 |
def is_music_fallback(self, text):
|
| 79 |
-
"""
|
| 80 |
clean = text.lower()
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
notes = len(re.findall(r"[drmfslt]", clean))
|
| 83 |
-
seps = len(re.findall(r"[:|]", clean))
|
|
|
|
|
|
|
| 84 |
return notes >= 3 and seps >= 1
|
| 85 |
|
| 86 |
def clean_rhythm_text(self, text):
|
|
@@ -141,18 +155,16 @@ class MasterEngine:
|
|
| 141 |
|
| 142 |
def generate_midi_bytes(self, html_content):
|
| 143 |
try:
|
| 144 |
-
# 1.
|
| 145 |
-
# On tente d'abord la décompression si c'est le format compressé
|
| 146 |
match = re.search(r'const b="([^"]+)"', html_content)
|
|
|
|
| 147 |
if match:
|
| 148 |
try:
|
| 149 |
svg = zlib.decompress(base64.b64decode(match.group(1))).decode('utf-8')
|
| 150 |
soup = BeautifulSoup(svg, 'html.parser')
|
| 151 |
-
except:
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
else:
|
| 155 |
-
# Si pas compressé, on parse direct
|
| 156 |
soup = BeautifulSoup(html_content, 'html.parser')
|
| 157 |
|
| 158 |
raw_items = []
|
|
@@ -165,9 +177,15 @@ class MasterEngine:
|
|
| 165 |
raw_items.append({'x': x, 'y': y, 'text': txt})
|
| 166 |
except: pass
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
if not raw_items: return None
|
| 169 |
|
| 170 |
-
# 2.
|
| 171 |
lines_map = {}
|
| 172 |
for item in raw_items:
|
| 173 |
found = False
|
|
@@ -177,50 +195,50 @@ class MasterEngine:
|
|
| 177 |
if not found: lines_map[item['y']] = [item]
|
| 178 |
|
| 179 |
all_lines_obj = []
|
| 180 |
-
full_text_blob = ""
|
| 181 |
|
| 182 |
for ky in sorted(lines_map.keys()):
|
| 183 |
row = sorted(lines_map[ky], key=lambda i: i['x'])
|
| 184 |
txt_parts = []
|
| 185 |
last_x = -100
|
| 186 |
for i in row:
|
| 187 |
-
if i['x'] - last_x > 12: txt_parts.append(" ")
|
| 188 |
txt_parts.append(i['text'])
|
| 189 |
last_x = i['x'] + len(i['text'])*5
|
| 190 |
full_line = "".join(txt_parts).strip()
|
| 191 |
all_lines_obj.append({'y': ky, 'text': full_line})
|
| 192 |
full_text_blob += " " + full_line
|
| 193 |
|
| 194 |
-
# 3.
|
| 195 |
root_note = 60
|
| 196 |
m = re.search(r"D[oô]\s*dia\s*([A-G][b#]?)", full_text_blob, re.IGNORECASE)
|
| 197 |
if m:
|
| 198 |
k = m.group(1).upper()
|
| 199 |
root_note = self.key_signatures.get(k, 60)
|
| 200 |
|
| 201 |
-
# 4.
|
| 202 |
valid_lines = []
|
| 203 |
|
| 204 |
-
#
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
| 218 |
|
| 219 |
-
if not valid_lines:
|
| 220 |
-
print("❌ Aucune ligne valide trouvée.")
|
| 221 |
-
return None
|
| 222 |
|
| 223 |
-
# 5.
|
| 224 |
threshold = self.safe_threshold([l['y'] for l in valid_lines])
|
| 225 |
systems = []
|
| 226 |
current = []
|
|
@@ -234,7 +252,7 @@ class MasterEngine:
|
|
| 234 |
if len(current) == 4: systems.append(current); current = []
|
| 235 |
if current: systems.append(current)
|
| 236 |
|
| 237 |
-
# 6.
|
| 238 |
midi = MIDIFile(1)
|
| 239 |
midi.addTempo(0, 0, TEMPO)
|
| 240 |
cursor = 0.0
|
|
@@ -260,8 +278,7 @@ class MasterEngine:
|
|
| 260 |
midi.addNote(0, channel, int(n[0]), n[1], n[2], VELOCITY)
|
| 261 |
has_notes = True
|
| 262 |
active_notes = []
|
| 263 |
-
trk_cursor += 1.0
|
| 264 |
-
continue
|
| 265 |
|
| 266 |
for val, dur in notes_in_beat:
|
| 267 |
if val == 'SUSTAIN':
|
|
@@ -272,7 +289,6 @@ class MasterEngine:
|
|
| 272 |
has_notes = True
|
| 273 |
active_notes = []
|
| 274 |
active_notes.append([val, trk_cursor, dur])
|
| 275 |
-
|
| 276 |
trk_cursor += dur
|
| 277 |
|
| 278 |
for n in active_notes:
|
|
@@ -280,31 +296,26 @@ class MasterEngine:
|
|
| 280 |
has_notes = True
|
| 281 |
|
| 282 |
if trk_cursor - cursor > max_dur: max_dur = trk_cursor - cursor
|
| 283 |
-
|
| 284 |
cursor += max_dur + 0.2
|
| 285 |
|
| 286 |
if has_notes:
|
| 287 |
buffer = io.BytesIO()
|
| 288 |
midi.writeFile(buffer)
|
| 289 |
-
print(f"✅ Génération réussie ({method}): {len(systems)} systèmes.")
|
| 290 |
return buffer.getvalue()
|
| 291 |
|
| 292 |
return None
|
| 293 |
|
| 294 |
except Exception as e:
|
| 295 |
-
print(f"⚠️ Erreur interne: {e}")
|
| 296 |
traceback.print_exc()
|
| 297 |
return None
|
| 298 |
|
| 299 |
-
#
|
| 300 |
engine = MasterEngine()
|
| 301 |
|
| 302 |
-
# --- ROUTE API ---
|
| 303 |
@app.post("/convert")
|
| 304 |
async def convert_solfa(html_code: str = Form(...)):
|
| 305 |
midi_data = engine.generate_midi_bytes(html_code)
|
| 306 |
-
|
| 307 |
if midi_data:
|
| 308 |
return Response(content=midi_data, media_type="audio/midi")
|
| 309 |
else:
|
| 310 |
-
return Response(status_code=400, content="
|
|
|
|
| 7 |
import base64
|
| 8 |
import statistics
|
| 9 |
import traceback
|
| 10 |
+
import sys
|
| 11 |
+
# On importe le nécessaire, mais on chargera l'IA prudemment
|
| 12 |
from bs4 import BeautifulSoup
|
| 13 |
from midiutil import MIDIFile
|
| 14 |
|
| 15 |
app = FastAPI()
|
| 16 |
|
|
|
|
| 17 |
app.add_middleware(
|
| 18 |
CORSMiddleware,
|
| 19 |
allow_origins=["*"],
|
|
|
|
| 27 |
TEMPO = 100
|
| 28 |
VELOCITY = 100
|
| 29 |
|
| 30 |
+
# --- MOTEUR PRINCIPAL ---
|
| 31 |
class MasterEngine:
|
| 32 |
def __init__(self):
|
| 33 |
+
self.model = None
|
| 34 |
+
self.forbidden = set("bkghjqwxyzncuvBKGHJQWXYZNCUV1234567890")
|
| 35 |
+
|
| 36 |
+
# Tentative de chargement sécurisée
|
| 37 |
+
print("🛠️ Initialisation du moteur...")
|
| 38 |
try:
|
| 39 |
+
# On vérifie d'abord si sklearn est installé
|
| 40 |
+
import sklearn
|
| 41 |
+
print(f"ℹ️ Version Scikit-learn du serveur: {sklearn.__version__}")
|
| 42 |
+
|
| 43 |
with open(BRAIN_FILE, "rb") as f:
|
| 44 |
self.model = pickle.load(f)
|
| 45 |
+
print("✅ Cerveau IA chargé avec succès !")
|
| 46 |
except Exception as e:
|
| 47 |
+
print(f"⚠️ AVERTISSEMENT : Le cerveau IA n'a pas pu être chargé.")
|
| 48 |
+
print(f"⚠️ Raison : {e}")
|
| 49 |
+
print("⚠️ -> Passage automatique en mode ALGORITHMIQUE STRICT (Sans IA)")
|
| 50 |
self.model = None
|
| 51 |
+
|
| 52 |
+
# Mapping Solfège
|
|
|
|
|
|
|
| 53 |
self.chromatic_map = {
|
| 54 |
'd': 0, 'di': 1, 'de': 11, 'r': 2, 'ri': 3, 'ra': 1, 'm': 4, 'ma': 3,
|
| 55 |
'f': 5, 'fi': 6, 's': 7, 'si': 8, 'se': 6, 'l': 9, 'li': 10, 'la': 8, 't': 11, 'ta': 10
|
| 56 |
}
|
| 57 |
|
|
|
|
| 58 |
self.key_signatures = {
|
| 59 |
'C': 60, 'D': 62, 'E': 64, 'F': 65, 'G': 67, 'A': 69, 'B': 71,
|
| 60 |
'CB': 59, 'DB': 61, 'EB': 63, 'GB': 66, 'AB': 68, 'BB': 70,
|
|
|
|
| 73 |
return [notes/length, seps/length, mods/length, bad, density]
|
| 74 |
|
| 75 |
def is_music_ai(self, text):
|
| 76 |
+
"""Utilise l'IA si dispo, sinon renvoie False"""
|
| 77 |
if not self.model: return False
|
| 78 |
+
if "dia" in text.lower() and len(text) < 20: return False
|
|
|
|
| 79 |
try:
|
| 80 |
+
feats = self.extract_features(text)
|
| 81 |
return self.model.predict([feats])[0] == 1
|
| 82 |
except:
|
| 83 |
return False
|
| 84 |
|
| 85 |
def is_music_fallback(self, text):
|
| 86 |
+
"""ALGO STRICT : Utilisé si l'IA plante ou est absente"""
|
| 87 |
clean = text.lower()
|
| 88 |
+
|
| 89 |
+
# 1. Liste noire de mots malgaches courants (Paroles)
|
| 90 |
+
bad_words = ["dia", "fa", "ny", "ho", "tsy", "misy", "hira", "ffpm", "p.", "andri"]
|
| 91 |
+
if any(w in clean.split() for w in bad_words): return False
|
| 92 |
+
|
| 93 |
+
# 2. Vérification des notes
|
| 94 |
notes = len(re.findall(r"[drmfslt]", clean))
|
| 95 |
+
seps = len(re.findall(r"[:|]", clean)) # Séparateurs de mesure
|
| 96 |
+
|
| 97 |
+
# Une ligne de solfa DOIT avoir des séparateurs et au moins 3 notes
|
| 98 |
return notes >= 3 and seps >= 1
|
| 99 |
|
| 100 |
def clean_rhythm_text(self, text):
|
|
|
|
| 155 |
|
| 156 |
def generate_midi_bytes(self, html_content):
|
| 157 |
try:
|
| 158 |
+
# 1. DECOMPRESSION & PARSING
|
|
|
|
| 159 |
match = re.search(r'const b="([^"]+)"', html_content)
|
| 160 |
+
soup = None
|
| 161 |
if match:
|
| 162 |
try:
|
| 163 |
svg = zlib.decompress(base64.b64decode(match.group(1))).decode('utf-8')
|
| 164 |
soup = BeautifulSoup(svg, 'html.parser')
|
| 165 |
+
except: pass
|
| 166 |
+
|
| 167 |
+
if not soup:
|
|
|
|
|
|
|
| 168 |
soup = BeautifulSoup(html_content, 'html.parser')
|
| 169 |
|
| 170 |
raw_items = []
|
|
|
|
| 177 |
raw_items.append({'x': x, 'y': y, 'text': txt})
|
| 178 |
except: pass
|
| 179 |
|
| 180 |
+
# Fallback Regex si parsing HTML échoue
|
| 181 |
+
if not raw_items:
|
| 182 |
+
raw_matches = re.findall(r'<text[^>]*y="([\d\.]+)"[^>]*>([^<]+)</text>', str(soup))
|
| 183 |
+
for y_str, txt in raw_matches:
|
| 184 |
+
raw_items.append({'x': 0, 'y': float(y_str), 'text': txt})
|
| 185 |
+
|
| 186 |
if not raw_items: return None
|
| 187 |
|
| 188 |
+
# 2. RECONSTITUTION LIGNES
|
| 189 |
lines_map = {}
|
| 190 |
for item in raw_items:
|
| 191 |
found = False
|
|
|
|
| 195 |
if not found: lines_map[item['y']] = [item]
|
| 196 |
|
| 197 |
all_lines_obj = []
|
| 198 |
+
full_text_blob = ""
|
| 199 |
|
| 200 |
for ky in sorted(lines_map.keys()):
|
| 201 |
row = sorted(lines_map[ky], key=lambda i: i['x'])
|
| 202 |
txt_parts = []
|
| 203 |
last_x = -100
|
| 204 |
for i in row:
|
| 205 |
+
if i['x'] - last_x > 12: txt_parts.append(" ")
|
| 206 |
txt_parts.append(i['text'])
|
| 207 |
last_x = i['x'] + len(i['text'])*5
|
| 208 |
full_line = "".join(txt_parts).strip()
|
| 209 |
all_lines_obj.append({'y': ky, 'text': full_line})
|
| 210 |
full_text_blob += " " + full_line
|
| 211 |
|
| 212 |
+
# 3. TONALITE
|
| 213 |
root_note = 60
|
| 214 |
m = re.search(r"D[oô]\s*dia\s*([A-G][b#]?)", full_text_blob, re.IGNORECASE)
|
| 215 |
if m:
|
| 216 |
k = m.group(1).upper()
|
| 217 |
root_note = self.key_signatures.get(k, 60)
|
| 218 |
|
| 219 |
+
# 4. FILTRAGE
|
| 220 |
valid_lines = []
|
| 221 |
|
| 222 |
+
# Strategie : On privilégie le Fallback algorithmique car il est plus sûr si l'IA déconne
|
| 223 |
+
# L'IA sert de validation supplémentaire si elle est là
|
| 224 |
+
for obj in all_lines_obj:
|
| 225 |
+
txt = obj['text']
|
| 226 |
+
is_ok = False
|
| 227 |
+
|
| 228 |
+
# Test Algorithmique d'abord (Rapide et sûr)
|
| 229 |
+
if self.is_music_fallback(txt):
|
| 230 |
+
is_ok = True
|
| 231 |
+
|
| 232 |
+
# Test IA si chargé (pour récupérer des cas limites)
|
| 233 |
+
elif self.model and self.is_music_ai(txt):
|
| 234 |
+
is_ok = True
|
| 235 |
+
|
| 236 |
+
if is_ok:
|
| 237 |
+
valid_lines.append(obj)
|
| 238 |
|
| 239 |
+
if not valid_lines: return None
|
|
|
|
|
|
|
| 240 |
|
| 241 |
+
# 5. GROUPEMENT
|
| 242 |
threshold = self.safe_threshold([l['y'] for l in valid_lines])
|
| 243 |
systems = []
|
| 244 |
current = []
|
|
|
|
| 252 |
if len(current) == 4: systems.append(current); current = []
|
| 253 |
if current: systems.append(current)
|
| 254 |
|
| 255 |
+
# 6. MIDI
|
| 256 |
midi = MIDIFile(1)
|
| 257 |
midi.addTempo(0, 0, TEMPO)
|
| 258 |
cursor = 0.0
|
|
|
|
| 278 |
midi.addNote(0, channel, int(n[0]), n[1], n[2], VELOCITY)
|
| 279 |
has_notes = True
|
| 280 |
active_notes = []
|
| 281 |
+
trk_cursor += 1.0; continue
|
|
|
|
| 282 |
|
| 283 |
for val, dur in notes_in_beat:
|
| 284 |
if val == 'SUSTAIN':
|
|
|
|
| 289 |
has_notes = True
|
| 290 |
active_notes = []
|
| 291 |
active_notes.append([val, trk_cursor, dur])
|
|
|
|
| 292 |
trk_cursor += dur
|
| 293 |
|
| 294 |
for n in active_notes:
|
|
|
|
| 296 |
has_notes = True
|
| 297 |
|
| 298 |
if trk_cursor - cursor > max_dur: max_dur = trk_cursor - cursor
|
|
|
|
| 299 |
cursor += max_dur + 0.2
|
| 300 |
|
| 301 |
if has_notes:
|
| 302 |
buffer = io.BytesIO()
|
| 303 |
midi.writeFile(buffer)
|
|
|
|
| 304 |
return buffer.getvalue()
|
| 305 |
|
| 306 |
return None
|
| 307 |
|
| 308 |
except Exception as e:
|
|
|
|
| 309 |
traceback.print_exc()
|
| 310 |
return None
|
| 311 |
|
| 312 |
+
# Initialisation du moteur (chargement sécurisé)
|
| 313 |
engine = MasterEngine()
|
| 314 |
|
|
|
|
| 315 |
@app.post("/convert")
|
| 316 |
async def convert_solfa(html_code: str = Form(...)):
|
| 317 |
midi_data = engine.generate_midi_bytes(html_code)
|
|
|
|
| 318 |
if midi_data:
|
| 319 |
return Response(content=midi_data, media_type="audio/midi")
|
| 320 |
else:
|
| 321 |
+
return Response(status_code=400, content="Echec generation")
|