GuanHuaYu student commited on
Commit ·
31d480d
1
Parent(s): a2b637a
Update
Browse filesFiles changed (6)
- .history/app_20251009231256.pyAdded+2282
- .history/app_20251009231310.pyAdded+2402
- .history/app_20251009232235.pyAdded+2402
- .history/app_20251009232247.pyAdded+2431
- .history/app_20251009232414.pyAdded+2431
- app.py+232-83
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282"""Gradio front-end for Fault_Classification_PMU_Data models.
The application loads a CNN-LSTM model (and accompanying scaler/metadata)produced by ``fault_classification_pmu.py`` and exposes a streamlinedprediction interface optimised for Hugging Face Spaces deployment. It supportsraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""from __future__ import annotations
import jsonimport osimport shutil
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "-1")os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0")
import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import gradio as grimport joblibimport numpy as npimport pandas as pdimport requestsfrom huggingface_hub import hf_hub_downloadfrom tensorflow.keras.models import load_model
from fault_classification_pmu import ( DEFAULT_FEATURE_COLUMNS as TRAINING_DEFAULT_FEATURE_COLUMNS, LABEL_GUESS_CANDIDATES as TRAINING_LABEL_GUESSES, train_from_dataframe,)
# --------------------------------------------------------------------------------------# Configuration# --------------------------------------------------------------------------------------DEFAULT_FEATURE_COLUMNS: List[str] = list(TRAINING_DEFAULT_FEATURE_COLUMNS)DEFAULT_SEQUENCE_LENGTH = 32DEFAULT_STRIDE = 4
LOCAL_MODEL_FILE = os.environ.get("PMU_MODEL_FILE", "pmu_cnn_lstm_model.keras")LOCAL_SCALER_FILE = os.environ.get("PMU_SCALER_FILE", "pmu_feature_scaler.pkl")LOCAL_METADATA_FILE = os.environ.get("PMU_METADATA_FILE", "pmu_metadata.json")
MODEL_OUTPUT_DIR = Path(os.environ.get("PMU_MODEL_DIR", "model")).resolve()MODEL_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
HUB_REPO = os.environ.get("PMU_HUB_REPO", "")HUB_MODEL_FILENAME = os.environ.get("PMU_HUB_MODEL_FILENAME", LOCAL_MODEL_FILE)HUB_SCALER_FILENAME = os.environ.get("PMU_HUB_SCALER_FILENAME", LOCAL_SCALER_FILE)HUB_METADATA_FILENAME = os.environ.get("PMU_HUB_METADATA_FILENAME", LOCAL_METADATA_FILE)
ENV_MODEL_PATH = "PMU_MODEL_PATH"ENV_SCALER_PATH = "PMU_SCALER_PATH"ENV_METADATA_PATH = "PMU_METADATA_PATH"
# --------------------------------------------------------------------------------------# Utility functions for loading artifacts# --------------------------------------------------------------------------------------
def download_from_hub(filename: str) -> Optional[Path]: if not HUB_REPO or not filename: return None try: print(f"Downloading {filename} from {HUB_REPO} ...") # Add timeout to prevent hanging path = hf_hub_download(repo_id=HUB_REPO, filename=filename) print("Downloaded", path) return Path(path) except Exception as exc: # pragma: no cover - logging convenience print("Failed to download", filename, "from", HUB_REPO, ":", exc) print("Continuing without pre-trained model...") return None
def resolve_artifact(local_name: str, env_var: str, hub_filename: str) -> Optional[Path]: print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}") candidates = [Path(local_name)] if local_name else [] if local_name: candidates.append(MODEL_OUTPUT_DIR / Path(local_name).name) env_value = os.environ.get(env_var) if env_value: candidates.append(Path(env_value))
for candidate in candidates: if candidate and candidate.exists(): print(f"Found local artifact: {candidate}") return candidate
print(f"No local artifacts found, checking hub...") # Only try to download if we have a hub repo configured if HUB_REPO: return download_from_hub(hub_filename) else: print("No HUB_REPO configured, skipping download") return None
def load_metadata(path: Optional[Path]) -> Dict: if path and path.exists(): try: return json.loads(path.read_text()) except Exception as exc: # pragma: no cover - metadata parsing errors print("Failed to read metadata", path, exc) return {}
def try_load_scaler(path: Optional[Path]): if not path: return None try: scaler = joblib.load(path) print("Loaded scaler from", path) return scaler except Exception as exc: print("Failed to load scaler", path, exc) return None
# Initialize paths with error handlingprint("Starting application initialization...")try: MODEL_PATH = resolve_artifact(LOCAL_MODEL_FILE, ENV_MODEL_PATH, HUB_MODEL_FILENAME) print(f"Model path resolved: {MODEL_PATH}")except Exception as e: print(f"Model path resolution failed: {e}") MODEL_PATH = None
try: SCALER_PATH = resolve_artifact(LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME) print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e: print(f"Scaler path resolution failed: {e}") SCALER_PATH = None
try: METADATA_PATH = resolve_artifact(LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME) print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e: print(f"Metadata path resolution failed: {e}") METADATA_PATH = None
try: METADATA = load_metadata(METADATA_PATH) print(f"Metadata loaded: {len(METADATA)} entries")except Exception as e: print(f"Metadata loading failed: {e}") METADATA = {}
# Queuing configurationQUEUE_MAX_SIZE = 32# Apply a small per-event concurrency limit to avoid relying on the deprecated# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2
def try_load_model(path: Optional[Path], model_type: str, model_format: str): if not path: return None try: if model_type == "svm" or model_format == "joblib": model = joblib.load(path) else: model = load_model(path) print("Loaded model from", path) return model except Exception as exc: # pragma: no cover - runtime diagnostics print("Failed to load model", path, exc) return None
FEATURE_COLUMNS: List[str] = list(DEFAULT_FEATURE_COLUMNS)LABEL_CLASSES: List[str] = []LABEL_COLUMN: str = "Fault"SEQUENCE_LENGTH: int = DEFAULT_SEQUENCE_LENGTHDEFAULT_WINDOW_STRIDE: int = DEFAULT_STRIDEMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"
def _model_output_path(filename: str) -> str: return str(MODEL_OUTPUT_DIR / Path(filename).name)
MODEL_FILENAME_BY_TYPE: Dict[str, str] = { "cnn_lstm": Path(LOCAL_MODEL_FILE).name, "tcn": "pmu_tcn_model.keras", "svm": "pmu_svm_model.joblib",}
REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path(os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
TRAINING_DATA_REPO = os.environ.get("PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)
GITHUB_CONTENT_CACHE: Dict[str, List[Dict[str, Any]]] = {}
APP_CSS = """#available-files-section { position: relative; display: flex; flex-direction: column; gap: 0.75rem; border-radius: 0.75rem;}
#available-files-grid { position: relative; overflow: visible;}
#available-files-grid .form { position: relative; min-height: 16rem;}
#available-files-section:has(.gradio-loading) { isolation: isolate;}
#available-files-grid .wrap { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.5rem; max-height: 24rem; min-height: 16rem; overflow-y: auto; padding-right: 0.25rem;}
#available-files-grid .wrap > div { min-width: 0;}
#available-files-grid .wrap label { margin: 0; display: flex; align-items: center; padding: 0.45rem 0.65rem; border-radius: 0.65rem; background-color: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease, border-color 0.2s ease; min-height: 2.5rem;}
#available-files-grid .wrap label:hover { background-color: rgba(90, 200, 250, 0.16); border-color: rgba(90, 200, 250, 0.4);}
#available-files-grid .wrap label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
#available-files-grid .gradio-loading { position: absolute; inset: 0; width: auto; height: auto; min-height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.72); border-radius: 0.75rem; z-index: 10; padding: 1.5rem; pointer-events: auto;}
#available-files-grid .gradio-loading > * { width: 100%;}
#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,#available-files-grid .gradio-loading [role="progressbar"],#available-files-grid .gradio-loading .wrap,#available-files-grid .gradio-loading .inner { width: 100% !important; max-width: none !important;}
#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label { text-align: center;}
#date-browser-row { gap: 0.75rem;}
#date-browser-row .date-browser-column { flex: 1 1 0%; min-width: 0;}
#date-browser-row .date-browser-column > .gradio-dropdown,#date-browser-row .date-browser-column > .gradio-button { width: 100%;}
#date-browser-row .date-browser-column > .gradio-dropdown > div { width: 100%;}
#date-browser-row .date-browser-column .gradio-button { justify-content: center;}
#training-files-summary textarea { max-height: 12rem; overflow-y: auto;}
#download-selected-button { width: 100%; position: relative; z-index: 0;}
#download-selected-button .gradio-button { width: 100%; justify-content: center;}
#artifact-download-row { gap: 0.75rem;}
#artifact-download-row .artifact-download-button { flex: 1 1 0%; min-width: 0;}
#artifact-download-row .artifact-download-button .gradio-button { width: 100%; justify-content: center;}"""
def _github_cache_key(path: str) -> str: return path or "__root__"
def _github_api_url(path: str) -> str: clean_path = path.strip("/") base = f"https://api.github.com/repos/{TRAINING_DATA_REPO}/contents" if clean_path: return f"{base}/{clean_path}?ref={TRAINING_DATA_BRANCH}" return f"{base}?ref={TRAINING_DATA_BRANCH}"
def list_remote_directory(path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]: key = _github_cache_key(path) if not force_refresh and key in GITHUB_CONTENT_CACHE: return GITHUB_CONTENT_CACHE[key]
url = _github_api_url(path) response = requests.get(url, timeout=30) if response.status_code != 200: raise RuntimeError( f"GitHub API request failed for `{path or '.'}` (status {response.status_code})." )
payload = response.json() if not isinstance(payload, list): raise RuntimeError("Unexpected GitHub API payload. Expected a directory listing.")
GITHUB_CONTENT_CACHE[key] = payload return payload
def list_remote_years(force_refresh: bool = False) -> List[str]: entries = list_remote_directory("", force_refresh=force_refresh) years = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(years)
def list_remote_months(year: str, *, force_refresh: bool = False) -> List[str]: if not year: return [] entries = list_remote_directory(year, force_refresh=force_refresh) months = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(months)
def list_remote_days(year: str, month: str, *, force_refresh: bool = False) -> List[str]: if not year or not month: return [] entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh) days = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(days)
def list_remote_files(year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]: if not year or not month or not day: return [] entries = list_remote_directory( f"{year}/{month}/{day}", force_refresh=force_refresh ) files = [item["name"] for item in entries if item.get("type") == "file"] return sorted(files)
def download_repository_file(year: str, month: str, day: str, filename: str) -> Path: if not filename: raise ValueError("Filename cannot be empty when downloading repository data.")
relative_parts = [part for part in (year, month, day, filename) if part] if len(relative_parts) < 4: raise ValueError("Provide year, month, day, and filename to download a CSV.")
relative_path = "/".join(relative_parts) raw_url = ( f"https://raw.githubusercontent.com/{TRAINING_DATA_REPO}/" f"{TRAINING_DATA_BRANCH}/{relative_path}" )
response = requests.get(raw_url, stream=True, timeout=120) if response.status_code != 200: raise RuntimeError( f"Failed to download `{relative_path}` (status {response.status_code})." )
target_dir = TRAINING_DATA_DIR.joinpath(year, month, day) target_dir.mkdir(parents=True, exist_ok=True) target_path = target_dir / filename
with open(target_path, "wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): if chunk: handle.write(chunk)
return target_path
def _normalise_header(name: str) -> str: return str(name).strip().lower()
def guess_label_from_columns(columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]: if not columns: return preferred
lookup = {_normalise_header(col): str(col) for col in columns}
if preferred: preferred_stripped = preferred.strip() for col in columns: if str(col).strip() == preferred_stripped: return str(col) preferred_norm = _normalise_header(preferred) if preferred_norm in lookup: return lookup[preferred_norm]
for guess in TRAINING_LABEL_GUESSES: guess_norm = _normalise_header(guess) if guess_norm in lookup: return lookup[guess_norm]
for col in columns: if _normalise_header(col).startswith("fault"): return str(col)
return str(columns[0])
def summarise_training_files(paths: Sequence[str], notes: Sequence[str]) -> str: lines = [Path(path).name for path in paths] lines.extend(notes) return "\n".join(lines) if lines else "No training files available."
def read_training_status(status_file_path: str) -> str: """Read the current training status from file.""" try: if Path(status_file_path).exists(): with open(status_file_path, 'r') as f: return f.read().strip() except Exception: pass return "Training status unavailable"
def _persist_uploaded_file(file_obj) -> Optional[Path]: if file_obj is None: return None
if isinstance(file_obj, (str, Path)): source = Path(file_obj) original_name = source.name else: source = Path(getattr(file_obj, "name", "") or getattr(file_obj, "path", "")) original_name = getattr(file_obj, "orig_name", source.name) or source.name if not source or not source.exists(): return None
original_name = Path(original_name).name or source.name
base_path = Path(original_name) destination = TRAINING_UPLOAD_DIR / base_path.name counter = 1 while destination.exists(): suffix = base_path.suffix or ".csv" destination = TRAINING_UPLOAD_DIR / f"{base_path.stem}_{counter}{suffix}" counter += 1
shutil.copy2(source, destination) return destination
def prepare_training_paths( paths: Sequence[str], current_label: str, cleanup_missing: bool = False): valid_paths: List[str] = [] notes: List[str] = [] columns_map: Dict[str, str] = {} for path in paths: try: df = load_measurement_csv(path) except Exception as exc: # pragma: no cover - user file diagnostics notes.append(f"⚠️ Skipped {Path(path).name}: {exc}") if cleanup_missing: try: Path(path).unlink(missing_ok=True) except Exception: pass continue valid_paths.append(str(path)) for col in df.columns: columns_map[_normalise_header(col)] = str(col)
summary = summarise_training_files(valid_paths, notes) preferred = current_label or LABEL_COLUMN dropdown_choices = sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN] guessed = guess_label_from_columns(dropdown_choices, preferred) dropdown_value = guessed or preferred or LABEL_COLUMN
return valid_paths, summary, gr.update(choices=dropdown_choices, value=dropdown_value)
def append_training_files(new_files, existing_paths: Sequence[str], current_label: str): if isinstance(existing_paths, (str, Path)): paths: List[str] = [str(existing_paths)] elif existing_paths is None: paths = [] else: paths = list(existing_paths) if new_files: for file in new_files: persisted = _persist_uploaded_file(file) if persisted is None: continue path_str = str(persisted) if path_str not in paths: paths.append(path_str)
return prepare_training_paths(paths, current_label, cleanup_missing=True)
def load_repository_training_files(current_label: str, force_refresh: bool = False): if force_refresh: # Clearing the cache is enough because downloads are now on-demand. for cached in list(TRAINING_DATA_DIR.glob("*")): # On refresh we keep previously downloaded files; no deletion required. # The flag triggers downstream UI updates only. break
csv_paths = sorted( str(path) for path in TRAINING_DATA_DIR.rglob("*.csv") if path.is_file() ) if not csv_paths: message = ( "No local database CSVs are available yet. Use the database browser " "below to download specific days before training." ) default_label = current_label or LABEL_COLUMN or "Fault" return ( [], message, gr.update(choices=[default_label], value=default_label), message, )
valid_paths, summary, label_update = prepare_training_paths( csv_paths, current_label, cleanup_missing=False )
info = ( f"Ready with {len(valid_paths)} CSV file(s) cached locally under " f"the database cache `{TRAINING_DATA_DIR}`." )
return valid_paths, summary, label_update, info
def refresh_remote_browser(force_refresh: bool = False): if force_refresh: GITHUB_CONTENT_CACHE.clear() try: years = list_remote_years(force_refresh=force_refresh) if years: message = "Select a year, month, and day to list available CSV files." else: message = ( "⚠️ No directories were found in the database root. Verify the upstream " "structure." ) return ( gr.update(choices=years, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to query database: {exc}", )
def on_year_change(year: Optional[str]): if not year: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a year to continue.", ) try: months = list_remote_months(year) message = ( f"Year `{year}` selected. Choose a month to drill down." if months else f"⚠️ No months available under `{year}`." ) return ( gr.update(choices=months, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list months: {exc}", )
def on_month_change(year: Optional[str], month: Optional[str]): if not year or not month: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a month to continue.", ) try: days = list_remote_days(year, month) message = ( f"Month `{year}/{month}` ready. Pick a day to view files." if days else f"⚠️ No day folders found under `{year}/{month}`." ) return ( gr.update(choices=days, value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list days: {exc}", )
def on_day_change(year: Optional[str], month: Optional[str], day: Optional[str]): if not year or not month or not day: return ( gr.update(choices=[], value=[]), "Select a day to load file names.", ) try: files = list_remote_files(year, month, day) message = ( f"{len(files)} file(s) available for `{year}/{month}/{day}`." if files else f"⚠️ No CSV files found under `{year}/{month}/{day}`." ) return ( gr.update(choices=files, value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=[]), f"⚠️ Failed to list files: {exc}", )
def download_selected_files( year: Optional[str], month: Optional[str], day: Optional[str], filenames: Sequence[str], current_label: str,): if not filenames: message = "Select at least one CSV before downloading." local = load_repository_training_files(current_label) return (*local, gr.update(), message)
success: List[str] = [] notes: List[str] = [] for filename in filenames: try: path = download_repository_file(year or "", month or "", day or "", filename) success.append(str(path)) except Exception as exc: notes.append(f"⚠️ {filename}: {exc}")
local = load_repository_training_files(current_label)
message_lines = [] if success: message_lines.append( f"Downloaded {len(success)} file(s) to the database cache `{TRAINING_DATA_DIR}`." ) if notes: message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_day_bundle( year: Optional[str], month: Optional[str], day: Optional[str], current_label: str,): if not (year and month and day): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year, month, and day before downloading an entire day.", )
try: files = list_remote_files(year, month, day) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to list CSVs for `{year}/{month}/{day}`: {exc}", )
if not files: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No CSV files were found for `{year}/{month}/{day}`.", )
result = list(download_selected_files(year, month, day, files, current_label)) result[-1] = ( f"Downloaded all {len(files)} CSV file(s) for `{year}/{month}/{day}`.\n" f"{result[-1]}" ) return tuple(result)
def download_month_bundle( year: Optional[str], month: Optional[str], current_label: str): if not (year and month): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year and month before downloading an entire month.", )
try: days = list_remote_days(year, month) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate days for `{year}/{month}`: {exc}", )
if not days: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No day folders were found for `{year}/{month}`.", )
downloaded = 0 notes: List[str] = [] for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append( f"⚠️ {year}/{month}/{day}/{filename}: {exc}" )
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}/{month}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_year_bundle(year: Optional[str], current_label: str): if not year: local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year before downloading an entire year of CSVs.", )
try: months = list_remote_months(year) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate months for `{year}`: {exc}", )
if not months: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No month folders were found for `{year}`.", )
downloaded = 0 notes: List[str] = [] for month in months: try: days = list_remote_days(year, month) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}`: {exc}") continue if not days: notes.append(f"⚠️ No day folders in `{year}/{month}`.") continue for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append( f"⚠️ {year}/{month}/{day}/{filename}: {exc}" )
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def clear_downloaded_cache(current_label: str): status_message = "" try: if TRAINING_DATA_DIR.exists(): shutil.rmtree(TRAINING_DATA_DIR) TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True) status_message = ( f"Cleared all downloaded CSVs from database cache `{TRAINING_DATA_DIR}`." ) except Exception as exc: status_message = f"⚠️ Failed to clear database cache: {exc}"
local = load_repository_training_files(current_label, force_refresh=True) remote = list(refresh_remote_browser(force_refresh=False)) if status_message: previous = remote[-1] if isinstance(previous, str) and previous: remote[-1] = f"{status_message}\n{previous}" else: remote[-1] = status_message
return (*local, *remote)
def normalise_output_directory(directory: Optional[str]) -> Path: base = Path(directory or MODEL_OUTPUT_DIR) base = base.expanduser() if not base.is_absolute(): base = (Path.cwd() / base).resolve() return base
def resolve_output_path( directory: Optional[Union[Path, str]], filename: Optional[str], fallback: str) -> Path: if isinstance(directory, Path): base = directory else: base = normalise_output_directory(directory) candidate = Path(filename or "").expanduser() if str(candidate): if candidate.is_absolute(): return candidate return (base / candidate).resolve() return (base / fallback).resolve()
ARTIFACT_FILE_EXTENSIONS: Tuple[str, ...] = ( ".keras", ".h5", ".joblib", ".pkl", ".json", ".onnx", ".zip", ".txt",)
def gather_directory_choices(current: Optional[str]) -> Tuple[List[str], str]: base = normalise_output_directory(current or str(MODEL_OUTPUT_DIR)) candidates = {str(base)} try: for candidate in base.parent.iterdir(): if candidate.is_dir(): candidates.add(str(candidate.resolve())) except Exception: pass return sorted(candidates), str(base)
def gather_artifact_choices( directory: Optional[str], selection: Optional[str] = None) -> Tuple[List[Tuple[str, str]], Optional[str]]: base = normalise_output_directory(directory) choices: List[Tuple[str, str]] = [] selected_value: Optional[str] = None if base.exists(): try: artifacts = sorted( [ path for path in base.iterdir() if path.is_file() and ( not ARTIFACT_FILE_EXTENSIONS or path.suffix.lower() in ARTIFACT_FILE_EXTENSIONS ) ], key=lambda path: path.name.lower(), ) choices = [(artifact.name, str(artifact)) for artifact in artifacts] except Exception: choices = []
if selection and any(value == selection for _, value in choices): selected_value = selection elif choices: selected_value = choices[0][1]
return choices, selected_value
def download_button_state(path: Optional[Union[str, Path]]): if not path: return gr.update(value=None, visible=False) candidate = Path(path) if candidate.exists(): return gr.update(value=str(candidate), visible=True) return gr.update(value=None, visible=False)
def clear_training_files(): default_label = LABEL_COLUMN or "Fault" for cached_file in TRAINING_UPLOAD_DIR.glob("*"): try: if cached_file.is_file(): cached_file.unlink(missing_ok=True) except Exception: pass return ( [], "No training files selected.", gr.update(choices=[default_label], value=default_label), gr.update(value=None), )
PROJECT_OVERVIEW_MD = """## Project Overview
This project focuses on classifying faults in electrical transmission lines andgrid-connected photovoltaic (PV) systems by combining ensemble learningtechniques with deep neural architectures.
## Datasets
### Transmission Line Fault Dataset- 134,406 samples collected from Phasor Measurement Units (PMUs)- 14 monitored channels covering currents, voltages, magnitudes, frequency, and phase angles- Labels span symmetrical and asymmetrical faults: NF, L-G, LL, LL-G, LLL, and LLL-G- Time span: 0 to 5.7 seconds with high-frequency sampling
### Grid-Connected PV System Fault Dataset- 2,163,480 samples from 16 experimental scenarios- 14 features including PV array measurements (Ipv, Vpv, Vdc), three-phase currents/voltages, aggregate magnitudes (Iabc, Vabc), and frequency indicators (If, Vf)- Captures array, inverter, grid anomaly, feedback sensor, and MPPT controller faults at 9.9989 μs sampling intervals
## Data Format Quick Reference
Each measurement file may be comma or tab separated and typically exposes thefollowing ordered columns:
1. `Timestamp`2. `[325] UPMU_SUB22:FREQ` – system frequency (Hz)3. `[326] UPMU_SUB22:DFDT` – frequency rate-of-change4. `[327] UPMU_SUB22:FLAG` – PMU status flag5. `[328] UPMU_SUB22-L1:MAG` – phase A voltage magnitude6. `[329] UPMU_SUB22-L1:ANG` – phase A voltage angle7. `[330] UPMU_SUB22-L2:MAG` – phase B voltage magnitude8. `[331] UPMU_SUB22-L2:ANG` – phase B voltage angle9. `[332] UPMU_SUB22-L3:MAG` – phase C voltage magnitude10. `[333] UPMU_SUB22-L3:ANG` – phase C voltage angle11. `[334] UPMU_SUB22-C1:MAG` – phase A current magnitude12. `[335] UPMU_SUB22-C1:ANG` – phase A current angle13. `[336] UPMU_SUB22-C2:MAG` – phase B current magnitude14. `[337] UPMU_SUB22-C2:ANG` – phase B current angle15. `[338] UPMU_SUB22-C3:MAG` – phase C current magnitude16. `[339] UPMU_SUB22-C3:ANG` – phase C current angle
The training tab automatically downloads the latest CSV exports from the`VincentCroft/ThesisModelData` repository and concatenates them before buildingsliding windows.
## Models Developed
1. **Support Vector Machine (SVM)** – provides the classical machine learning baseline with balanced accuracy across both datasets (85% PMU / 83% PV).2. **CNN-LSTM** – couples convolutional feature extraction with temporal memory, achieving 92% PMU / 89% PV accuracy.3. **Temporal Convolutional Network (TCN)** – leverages dilated convolutions for long-range context and delivers the best trade-off between accuracy and training time (94% PMU / 91% PV).
## Results Summary
- **Transmission Line Fault Classification**: SVM 85%, CNN-LSTM 92%, TCN 94%- **PV System Fault Classification**: SVM 83%, CNN-LSTM 89%, TCN 91%
Use the **Inference** tab to score new PMU/PV windows and the **Training** tab tofine-tune or retrain any of the supported models directly within Hugging FaceSpaces. The logs panel will surface TensorBoard archives whenever deep-learningmodels are trained."""
def load_measurement_csv(path: str) -> pd.DataFrame: """Read a PMU/PV measurement file with flexible separators and column mapping."""
try: df = pd.read_csv(path, sep=None, engine="python", encoding="utf-8-sig") except Exception: df = None for separator in ("\t", ",", ";"): try: df = pd.read_csv(path, sep=separator, engine="python", encoding="utf-8-sig") break except Exception: df = None if df is None: raise
# Clean column names df.columns = [str(col).strip() for col in df.columns]
print(f"Loaded CSV with {len(df)} rows and {len(df.columns)} columns") print(f"Columns: {list(df.columns)}") print(f"Data shape: {df.shape}")
# Check if we have enough data for training if len(df) < 100: print(f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training.")
# Check for label column has_label = any(col.lower() in ['fault', 'label', 'class', 'target'] for col in df.columns) if not has_label: print("Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples.") df['Fault'] = 'Normal' # Add dummy label for training
# Create column mapping - map similar column names to expected format column_mapping = {} expected_cols = list(REQUIRED_PMU_COLUMNS)
# If we have at least the right number of numeric columns after Timestamp, use positional mapping if "Timestamp" in df.columns: numeric_cols = [col for col in df.columns if col != "Timestamp"] if len(numeric_cols) >= len(expected_cols): # Map by position (after Timestamp) for i, expected_col in enumerate(expected_cols): if i < len(numeric_cols): column_mapping[numeric_cols[i]] = expected_col
# Rename columns to match expected format df = df.rename(columns=column_mapping)
# Check if we have the required columns after mapping missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns] if missing: # If still missing, try a more flexible approach available_numeric = df.select_dtypes(include=[np.number]).columns.tolist() if len(available_numeric) >= len(expected_cols): # Use the first N numeric columns for i, expected_col in enumerate(expected_cols): if i < len(available_numeric): if available_numeric[i] not in df.columns: continue df = df.rename(columns={available_numeric[i]: expected_col})
# Recheck missing columns missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns]
if missing: missing_str = ", ".join(missing) available_str = ", ".join(df.columns.tolist()) raise ValueError( f"Missing required PMU feature columns: {missing_str}. " f"Available columns: {available_str}. " "Please ensure your CSV has the correct format with Timestamp followed by PMU measurements." )
return df
def apply_metadata(metadata: Dict[str, Any]) -> None: global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMAT FEATURE_COLUMNS = [str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS)] LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])] LABEL_COLUMN = str(metadata.get("label_column", "Fault")) SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH)) DEFAULT_WINDOW_STRIDE = int(metadata.get("stride", DEFAULT_STRIDE)) MODEL_TYPE = str(metadata.get("model_type", "cnn_lstm")).lower() MODEL_FORMAT = str( metadata.get("model_format", "joblib" if MODEL_TYPE == "svm" else "keras") ).lower()
apply_metadata(METADATA)
def sync_label_classes_from_model(model: Optional[object]) -> None: global LABEL_CLASSES if model is None: return if hasattr(model, "classes_"): LABEL_CLASSES = [str(label) for label in getattr(model, "classes_")] elif not LABEL_CLASSES and hasattr(model, "output_shape"): LABEL_CLASSES = [str(i) for i in range(int(model.output_shape[-1]))]
# Load model and scaler with error handlingprint("Loading model and scaler...")try: MODEL = try_load_model(MODEL_PATH, MODEL_TYPE, MODEL_FORMAT) print(f"Model loaded: {MODEL is not None}")except Exception as e: print(f"Model loading failed: {e}") MODEL = None
try: SCALER = try_load_scaler(SCALER_PATH) print(f"Scaler loaded: {SCALER is not None}")except Exception as e: print(f"Scaler loading failed: {e}") SCALER = None
try: sync_label_classes_from_model(MODEL) print("Label classes synchronized")except Exception as e: print(f"Label sync failed: {e}")
print("Application initialization completed.")print(f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")
def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None: global MODEL_PATH, SCALER_PATH, METADATA_PATH, MODEL, SCALER, METADATA MODEL_PATH = model_path SCALER_PATH = scaler_path METADATA_PATH = metadata_path METADATA = load_metadata(metadata_path) apply_metadata(METADATA) MODEL = try_load_model(model_path, MODEL_TYPE, MODEL_FORMAT) SCALER = try_load_scaler(scaler_path) sync_label_classes_from_model(MODEL)
# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------
def ensure_ready(): if MODEL is None or SCALER is None: raise RuntimeError( "The model and feature scaler are not available. Upload the trained model " "(for example `pmu_cnn_lstm_model.keras`, `pmu_tcn_model.keras`, or `pmu_svm_model.joblib`), " "the feature scaler (`pmu_feature_scaler.pkl`), and the metadata JSON (`pmu_metadata.json`) to the Space root " "or configure the Hugging Face Hub environment variables so the artifacts can be downloaded " "automatically." )
def parse_text_features(text: str) -> np.ndarray: cleaned = re.sub(r"[;\n\t]+", ",", text.strip()) arr = np.fromstring(cleaned, sep=",") if arr.size == 0: raise ValueError("No feature values were parsed. Please enter comma-separated numbers.") return arr.astype(np.float32)
def apply_scaler(sequences: np.ndarray) -> np.ndarray: if SCALER is None: return sequences shape = sequences.shape flattened = sequences.reshape(-1, shape[-1]) scaled = SCALER.transform(flattened) return scaled.reshape(shape)
def make_sliding_windows(data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray: if data.shape[0] < sequence_length: raise ValueError( f"The dataset contains {data.shape[0]} rows which is less than the requested sequence " f"length {sequence_length}. Provide more samples or reduce the sequence length." ) windows = [data[start : start + sequence_length] for start in range(0, data.shape[0] - sequence_length + 1, stride)] return np.stack(windows)
def dataframe_to_sequences( df: pd.DataFrame, *, sequence_length: int, stride: int, feature_columns: Sequence[str], drop_label: bool = True,) -> np.ndarray: work_df = df.copy() if drop_label and LABEL_COLUMN in work_df.columns: work_df = work_df.drop(columns=[LABEL_COLUMN]) if "Timestamp" in work_df.columns: work_df = work_df.sort_values("Timestamp")
available_cols = [c for c in feature_columns if c in work_df.columns] n_features = len(feature_columns) if available_cols and len(available_cols) == n_features: array = work_df[available_cols].astype(np.float32).to_numpy() return make_sliding_windows(array, sequence_length, stride)
numeric_df = work_df.select_dtypes(include=[np.number]) array = numeric_df.astype(np.float32).to_numpy() if array.shape[1] == n_features * sequence_length: return array.reshape(array.shape[0], sequence_length, n_features) if sequence_length == 1 and array.shape[1] == n_features: return array.reshape(array.shape[0], 1, n_features) raise ValueError( "CSV columns do not match the expected feature layout. Include the full PMU feature set " "or provide pre-shaped sliding window data." )
def label_name(index: int) -> str: if 0 <= index < len(LABEL_CLASSES): return str(LABEL_CLASSES[index]) return f"class_{index}"
def format_predictions(probabilities: np.ndarray) -> pd.DataFrame: rows: List[Dict[str, object]] = [] order = np.argsort(probabilities, axis=1)[:, ::-1] for idx, (prob_row, ranking) in enumerate(zip(probabilities, order)): top_idx = int(ranking[0]) top_label = label_name(top_idx) top_conf = float(prob_row[top_idx]) top3 = [f"{label_name(i)} ({prob_row[i]*100:.2f}%)" for i in ranking[:3]] rows.append( { "window": idx, "predicted_label": top_label, "confidence": round(top_conf, 4), "top3": " | ".join(top3), } ) return pd.DataFrame(rows)
def probabilities_to_json(probabilities: np.ndarray) -> List[Dict[str, object]]: payload: List[Dict[str, object]] = [] for idx, prob_row in enumerate(probabilities): payload.append( { "window": int(idx), "probabilities": {label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0])}, } ) return payload
def predict_sequences(sequences: np.ndarray) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: ensure_ready() sequences = apply_scaler(sequences.astype(np.float32)) if MODEL_TYPE == "svm": flattened = sequences.reshape(sequences.shape[0], -1) if hasattr(MODEL, "predict_proba"): probs = MODEL.predict_proba(flattened) else: raise RuntimeError("Loaded SVM model does not expose predict_proba. Retrain with probability=True.") else: probs = MODEL.predict(sequences, verbose=0) table = format_predictions(probs) json_probs = probabilities_to_json(probs) architecture = MODEL_TYPE.replace("_", "-").upper() status = f"Generated {len(sequences)} windows. {architecture} model output dimension: {probs.shape[1]}." return status, table, json_probs
def predict_from_text(text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: arr = parse_text_features(text) n_features = len(FEATURE_COLUMNS) if arr.size % n_features != 0: raise ValueError( f"The number of values ({arr.size}) is not a multiple of the feature dimension " f"({n_features}). Provide values in groups of {n_features}." ) timesteps = arr.size // n_features if timesteps != sequence_length: raise ValueError( f"Detected {timesteps} timesteps which does not match the configured sequence length " f"({sequence_length})." ) sequences = arr.reshape(1, sequence_length, n_features) status, table, probs = predict_sequences(sequences) status = f"Single window prediction complete. {status}" return status, table, probs
def predict_from_csv(file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: df = load_measurement_csv(file_obj.name) sequences = dataframe_to_sequences( df, sequence_length=sequence_length, stride=stride, feature_columns=FEATURE_COLUMNS, ) status, table, probs = predict_sequences(sequences) status = f"CSV processed successfully. Generated {len(sequences)} windows. {status}" return status, table, probs
# --------------------------------------------------------------------------------------# Training helpers# --------------------------------------------------------------------------------------
def classification_report_to_dataframe(report: Dict[str, Any]) -> pd.DataFrame: rows: List[Dict[str, Any]] = [] for label, metrics in report.items(): if isinstance(metrics, dict): row = {"label": label} for key, value in metrics.items(): if key == "support": row[key] = int(value) else: row[key] = round(float(value), 4) rows.append(row) else: rows.append({"label": label, "accuracy": round(float(metrics), 4)}) return pd.DataFrame(rows)
def confusion_matrix_to_dataframe(confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame: if not confusion: return pd.DataFrame() df = pd.DataFrame(confusion, index=list(labels), columns=list(labels)) df.index.name = "True Label" df.columns.name = "Predicted Label" return df
# --------------------------------------------------------------------------------------# Gradio interface# --------------------------------------------------------------------------------------
def build_interface() -> gr.Blocks: theme = gr.themes.Soft(primary_hue="sky", secondary_hue="blue", neutral_hue="gray").set( body_background_fill="#1f1f1f", body_text_color="#f5f5f5", block_background_fill="#262626", block_border_color="#333333", button_primary_background_fill="#5ac8fa", button_primary_background_fill_hover="#48b5eb", button_primary_border_color="#38bdf8", button_primary_text_color="#0f172a", button_secondary_background_fill="#3f3f46", button_secondary_text_color="#f5f5f5", )
def _normalise_directory_string(value: Optional[Union[str, Path]]) -> str: if value is None: return "" path = Path(value).expanduser() try: return str(path.resolve()) except Exception: return str(path)
with gr.Blocks(title="Fault Classification - PMU Data", theme=theme, css=APP_CSS) as demo: gr.Markdown("# Fault Classification for PMU & PV Data") gr.Markdown( "🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers." ) if MODEL is None or SCALER is None: gr.Markdown( "⚠️ **Artifacts Missing** — Upload `pmu_cnn_lstm_model.keras`, " "`pmu_feature_scaler.pkl`, and `pmu_metadata.json` to enable inference, " "or configure the Hugging Face Hub environment variables so they can be downloaded." ) else: class_count = len(LABEL_CLASSES) if LABEL_CLASSES else "unknown" gr.Markdown( f"Loaded a **{MODEL_TYPE.upper()}** model ({MODEL_FORMAT.upper()}) with " f"{len(FEATURE_COLUMNS)} features, sequence length **{SEQUENCE_LENGTH}**, and " f"{class_count} target classes. Use the tabs below to run inference or fine-tune " "the model with your own CSV files." )
with gr.Accordion("Feature Reference", open=False): gr.Markdown( f"Each time window expects **{len(FEATURE_COLUMNS)} features** ordered as follows:\n" + "\n".join(f"- {name}" for name in FEATURE_COLUMNS) ) gr.Markdown( f"Default training parameters: **sequence length = {SEQUENCE_LENGTH}**, " f"**stride = {DEFAULT_WINDOW_STRIDE}**. Adjust them in the tabs as needed." )
with gr.Tabs(): with gr.Tab("Overview"): gr.Markdown(PROJECT_OVERVIEW_MD) with gr.Tab("Inference"): gr.Markdown("## Run Inference") with gr.Row(): file_in = gr.File(label="Upload PMU CSV", file_types=[".csv"]) text_in = gr.Textbox( lines=4, label="Or paste a single window (comma separated)", placeholder="49.97772,1.215825E-38,...", )
with gr.Row(): sequence_length_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length (timesteps)", ) stride_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="CSV window stride", )
predict_btn = gr.Button("🚀 Run Inference", variant="primary") status_out = gr.Textbox(label="Status", interactive=False) table_out = gr.Dataframe( headers=["window", "predicted_label", "confidence", "top3"], label="Predictions", interactive=False, ) probs_out = gr.JSON(label="Per-window probabilities")
def _run_prediction(file_obj, text, sequence_length, stride): sequence_length = int(sequence_length) stride = int(stride) try: if file_obj is not None: return predict_from_csv(file_obj, sequence_length, stride) if text and text.strip(): return predict_from_text(text, sequence_length) return "Please upload a CSV file or provide feature values.", pd.DataFrame(), [] except Exception as exc: return f"Prediction failed: {exc}", pd.DataFrame(), []
predict_btn.click( _run_prediction, inputs=[file_in, text_in, sequence_length_input, stride_input], outputs=[status_out, table_out, probs_out], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Tab("Training"): gr.Markdown("## Train or Fine-tune the Model") gr.Markdown( "Training data is automatically downloaded from the database. " "Refresh the cache if new files are added upstream." )
training_files_state = gr.State([]) with gr.Row(): with gr.Column(scale=3): training_files_summary = gr.Textbox( label="Database training CSVs", value="Training dataset not loaded yet.", lines=4, interactive=False, elem_id="training-files-summary", ) with gr.Column(scale=2, min_width=240): dataset_info = gr.Markdown( "No local database CSVs downloaded yet.", ) dataset_refresh = gr.Button( "🔄 Reload dataset from database", variant="secondary", ) clear_cache_button = gr.Button( "🧹 Clear downloaded cache", variant="secondary", )
with gr.Accordion("📂 DataBaseBrowser", open=False): gr.Markdown( "Browse the upstream database by date and download only the CSVs you need." ) with gr.Row(elem_id="date-browser-row"): with gr.Column(scale=1, elem_classes=["date-browser-column"]): year_selector = gr.Dropdown(label="Year", choices=[]) year_download_button = gr.Button( "⬇️ Download year CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): month_selector = gr.Dropdown(label="Month", choices=[]) month_download_button = gr.Button( "⬇️ Download month CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): day_selector = gr.Dropdown(label="Day", choices=[]) day_download_button = gr.Button( "⬇️ Download day CSVs", variant="secondary" ) with gr.Column(elem_id="available-files-section"): available_files = gr.CheckboxGroup( label="Available CSV files", choices=[], value=[], elem_id="available-files-grid", ) download_button = gr.Button( "⬇️ Download selected CSVs", variant="secondary", elem_id="download-selected-button", ) repo_status = gr.Markdown( "Click 'Reload dataset from database' to fetch the directory tree." )
with gr.Row(): label_input = gr.Dropdown( value=LABEL_COLUMN, choices=[LABEL_COLUMN], allow_custom_value=True, label="Label column name", ) model_selector = gr.Radio( choices=["CNN-LSTM", "TCN", "SVM"], value=( "TCN" if MODEL_TYPE == "tcn" else ("SVM" if MODEL_TYPE == "svm" else "CNN-LSTM") ), label="Model architecture", ) sequence_length_train = gr.Slider( minimum=4, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length", ) stride_train = gr.Slider( minimum=1, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="Stride", )
model_default = MODEL_FILENAME_BY_TYPE.get( MODEL_TYPE, Path(LOCAL_MODEL_FILE).name )
with gr.Row(): validation_train = gr.Slider( minimum=0.05, maximum=0.4, step=0.05, value=0.2, label="Validation split", ) batch_train = gr.Slider( minimum=32, maximum=512, step=32, value=128, label="Batch size", ) epochs_train = gr.Slider( minimum=5, maximum=100, step=5, value=50, label="Epochs", )
directory_choices, directory_default = gather_directory_choices( str(MODEL_OUTPUT_DIR) ) artifact_choices, default_artifact = gather_artifact_choices( directory_default )
with gr.Row(): output_directory = gr.Dropdown( value=directory_default, label="Output directory", choices=directory_choices, allow_custom_value=True, ) model_name = gr.Textbox( value=model_default, label="Model output filename", ) scaler_name = gr.Textbox( value=Path(LOCAL_SCALER_FILE).name, label="Scaler output filename", ) metadata_name = gr.Textbox( value=Path(LOCAL_METADATA_FILE).name, label="Metadata output filename", )
with gr.Row(): artifact_browser = gr.Dropdown( label="Saved artifacts in directory", choices=artifact_choices, value=default_artifact, ) artifact_download_button = gr.DownloadButton( "⬇️ Download selected artifact", value=default_artifact, visible=bool(default_artifact), variant="secondary", )
def on_output_directory_change(selected_dir, current_selection): choices, normalised = gather_directory_choices(selected_dir) artifact_options, selected = gather_artifact_choices( normalised, current_selection ) return ( gr.update(choices=choices, value=normalised), gr.update(choices=artifact_options, value=selected), download_button_state(selected), )
def on_artifact_change(selected_path): return download_button_state(selected_path)
output_directory.change( on_output_directory_change, inputs=[output_directory, artifact_browser], outputs=[output_directory, artifact_browser, artifact_download_button], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
artifact_browser.change( on_artifact_change, inputs=[artifact_browser], outputs=[artifact_download_button], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Row(elem_id="artifact-download-row"): model_download_button = gr.DownloadButton( "⬇️ Download model file", value=None, visible=False, elem_classes=["artifact-download-button"], ) scaler_download_button = gr.DownloadButton( "⬇️ Download scaler file", value=None, visible=False, elem_classes=["artifact-download-button"], ) metadata_download_button = gr.DownloadButton( "⬇️ Download metadata file", value=None, visible=False, elem_classes=["artifact-download-button"], ) tensorboard_download_button = gr.DownloadButton( "⬇️ Download TensorBoard logs", value=None, visible=False, elem_classes=["artifact-download-button"], )
model_download_button.file_name = Path(LOCAL_MODEL_FILE).name scaler_download_button.file_name = Path(LOCAL_SCALER_FILE).name metadata_download_button.file_name = Path(LOCAL_METADATA_FILE).name tensorboard_download_button.file_name = "tensorboard_logs.zip"
tensorboard_toggle = gr.Checkbox( value=True, label="Enable TensorBoard logging (creates downloadable archive)", )
def _suggest_model_filename(choice: str, current_value: str): choice_key = (choice or "cnn_lstm").lower().replace("-", "_") suggested = MODEL_FILENAME_BY_TYPE.get( choice_key, Path(LOCAL_MODEL_FILE).name ) known_defaults = set(MODEL_FILENAME_BY_TYPE.values()) current_name = Path(current_value).name if current_value else "" if current_name and current_name not in known_defaults: return gr.update() return gr.update(value=suggested)
model_selector.change( _suggest_model_filename, inputs=[model_selector, model_name], outputs=model_name, )
with gr.Row(): train_button = gr.Button("🛠️ Start Training", variant="primary") progress_button = gr.Button("📊 Check Progress", variant="secondary")
# Training status display training_status = gr.Textbox(label="Training Status", interactive=False) report_output = gr.Dataframe(label="Classification report", interactive=False) history_output = gr.JSON(label="Training history") confusion_output = gr.Dataframe(label="Confusion matrix", interactive=False)
# Message area at the bottom for progress updates with gr.Accordion("📋 Progress Messages", open=True): progress_messages = gr.Textbox( label="Training Messages", lines=8, max_lines=20, interactive=False, autoscroll=True, placeholder="Click 'Check Progress' to see training updates..." ) with gr.Row(): gr.Button("🗑️ Clear Messages", variant="secondary").click( lambda: "", outputs=[progress_messages] )
def _run_training( file_paths, label_column, model_choice, sequence_length, stride, validation_split, batch_size, epochs, output_dir, model_filename, scaler_filename, metadata_filename, enable_tensorboard, ): base_dir = normalise_output_directory(output_dir) try: base_dir.mkdir(parents=True, exist_ok=True)
model_path = resolve_output_path( base_dir, model_filename, Path(LOCAL_MODEL_FILE).name, ) scaler_path = resolve_output_path( base_dir, scaler_filename, Path(LOCAL_SCALER_FILE).name, ) metadata_path = resolve_output_path( base_dir, metadata_filename, Path(LOCAL_METADATA_FILE).name, )
model_path.parent.mkdir(parents=True, exist_ok=True) scaler_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True)
# Create status file path for progress tracking status_file = model_path.parent / "training_status.txt"
# Initialize status with open(status_file, 'w') as f: f.write("Starting training setup...")
if not file_paths: raise ValueError( "No training CSVs were found in the database cache. " "Use 'Reload dataset from database' and try again." )
with open(status_file, 'w') as f: f.write("Loading and validating CSV files...")
available_paths = [path for path in file_paths if Path(path).exists()] missing_paths = [Path(path).name for path in file_paths if not Path(path).exists()] if not available_paths: raise ValueError( "Database training dataset is unavailable. Reload the dataset and retry." )
dfs = [load_measurement_csv(path) for path in available_paths] combined = pd.concat(dfs, ignore_index=True)
# Validate data size and provide recommendations total_samples = len(combined) if total_samples < 100: print(f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results.") print("Automatically switching to SVM for small dataset compatibility.") if model_choice in ["cnn_lstm", "tcn"]: model_choice = "svm" print(f"Model type changed to SVM for better small dataset performance.") if total_samples < 10: raise ValueError(f"Insufficient data: {total_samples} samples. Need at least 10 samples for training.")
label_column = (label_column or LABEL_COLUMN).strip() if not label_column: raise ValueError("Label column name cannot be empty.")
model_choice = (model_choice or "CNN-LSTM").lower().replace("-", "_") if model_choice not in {"cnn_lstm", "tcn", "svm"}: raise ValueError("Select CNN-LSTM, TCN, or SVM for the model architecture.")
with open(status_file, 'w') as f: f.write(f"Starting {model_choice.upper()} training with {len(combined)} samples...")
# Start training result = train_from_dataframe( combined, label_column=label_column, feature_columns=None, sequence_length=int(sequence_length), stride=int(stride), validation_split=float(validation_split), batch_size=int(batch_size), epochs=int(epochs), model_type=model_choice, model_path=model_path, scaler_path=scaler_path, metadata_path=metadata_path, enable_tensorboard=bool(enable_tensorboard), )
refresh_artifacts( Path(result["model_path"]), Path(result["scaler_path"]), Path(result["metadata_path"]), )
report_df = classification_report_to_dataframe(result["classification_report"]) confusion_df = confusion_matrix_to_dataframe(result["confusion_matrix"], result["class_names"]) tensorboard_dir = result.get("tensorboard_log_dir") tensorboard_zip = result.get("tensorboard_zip_path")
architecture = result["model_type"].replace("_", "-").upper() status = ( f"Training complete using a {architecture} architecture. " f"{result['num_sequences']} windows derived from " f"{result['num_samples']} rows across {len(available_paths)} file(s)." f" Artifacts saved to:" f"\n• Model: {result['model_path']}\n" f"• Scaler: {result['scaler_path']}\n" f"• Metadata: {result['metadata_path']}" )
status += f"\nLabel column used: {result.get('label_column', label_column)}"
if tensorboard_dir: status += ( f"\nTensorBoard logs directory: {tensorboard_dir}" f"\nRun `tensorboard --logdir \"{tensorboard_dir}\"` to inspect the training curves." "\nDownload the archive below to explore the run offline." )
if missing_paths: skipped = ", ".join(missing_paths) status = f"⚠️ Skipped missing files: {skipped}\n" + status
artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir), result["model_path"] )
return ( status, report_df, result["history"], confusion_df, download_button_state(result["model_path"]), download_button_state(result["scaler_path"]), download_button_state(result["metadata_path"]), download_button_state(tensorboard_zip), gr.update(value=result.get("label_column", label_column)), gr.update(choices=artifact_choices, value=selected_artifact), download_button_state(selected_artifact), ) except Exception as exc: artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir) ) return ( f"Training failed: {exc}", pd.DataFrame(), {}, pd.DataFrame(), download_button_state(None), download_button_state(None), download_button_state(None), download_button_state(None), gr.update(), gr.update(choices=artifact_choices, value=selected_artifact), download_button_state(selected_artifact), )
def _check_progress(output_dir, model_filename, current_messages): """Check training progress by reading status file and accumulate messages.""" model_path = resolve_output_path( output_dir, model_filename, Path(LOCAL_MODEL_FILE).name ) status_file = model_path.parent / "training_status.txt" status_message = read_training_status(str(status_file))
# Add timestamp to the message from datetime import datetime timestamp = datetime.now().strftime("%H:%M:%S") new_message = f"[{timestamp}] {status_message}"
# Accumulate messages, keeping last 50 lines to prevent overflow if current_messages: lines = current_messages.split('\n') lines.append(new_message) # Keep only last 50 lines if len(lines) > 50: lines = lines[-50:] accumulated_messages = '\n'.join(lines) else: accumulated_messages = new_message
return accumulated_messages
train_button.click( _run_training, inputs=[ training_files_state, label_input, model_selector, sequence_length_train, stride_train, validation_train, batch_train, epochs_train, output_directory, model_name, scaler_name, metadata_name, tensorboard_toggle, ], outputs=[ training_status, report_output, history_output, confusion_output, model_download_button, scaler_download_button, metadata_download_button, tensorboard_download_button, label_input, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
progress_button.click( _check_progress, inputs=[output_directory, model_name, progress_messages], outputs=[progress_messages], )
year_selector.change( on_year_change, inputs=[year_selector], outputs=[month_selector, day_selector, available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_selector.change( on_month_change, inputs=[year_selector, month_selector], outputs=[day_selector, available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_selector.change( on_day_change, inputs=[year_selector, month_selector, day_selector], outputs=[available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
download_button.click( download_selected_files, inputs=[ year_selector, month_selector, day_selector, available_files, label_input, ], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
year_download_button.click( download_year_bundle, inputs=[year_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_download_button.click( download_month_bundle, inputs=[year_selector, month_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_download_button.click( download_day_bundle, inputs=[year_selector, month_selector, day_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _reload_dataset(current_label): local = load_repository_training_files(current_label, force_refresh=True) remote = refresh_remote_browser(force_refresh=True) return (*local, *remote)
dataset_refresh.click( _reload_dataset, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
clear_cache_button.click( clear_downloaded_cache, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _initialise_dataset(): local = load_repository_training_files(LABEL_COLUMN, force_refresh=False) remote = refresh_remote_browser(force_refresh=False) return (*local, *remote)
demo.load( _initialise_dataset, inputs=None, outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], queue=False, )
return demo
# --------------------------------------------------------------------------------------# Launch helpers# --------------------------------------------------------------------------------------
def resolve_server_port() -> int: for env_var in ("PORT", "GRADIO_SERVER_PORT"): value = os.environ.get(env_var) if value: try: return int(value) except ValueError: print(f"Ignoring invalid port value from {env_var}: {value}") return 7860
def main(): print("Building Gradio interface...") try: demo = build_interface() print("Interface built successfully") except Exception as e: print(f"Failed to build interface: {e}") import traceback traceback.print_exc() return
print("Setting up queue...") try: demo.queue(max_size=QUEUE_MAX_SIZE) print("Queue configured") except Exception as e: print(f"Failed to configure queue: {e}")
try: port = resolve_server_port() print(f"Launching Gradio app on port {port}") demo.launch(server_name="0.0.0.0", server_port=port, show_error=True) except OSError as exc: print("Failed to launch on requested port:", exc) try: demo.launch(server_name="0.0.0.0", show_error=True) except Exception as e: print(f"Failed to launch completely: {e}") except Exception as e: print(f"Unexpected launch error: {e}") import traceback traceback.print_exc()
if __name__ == "__main__": print("="*50) print("PMU Fault Classification App Starting") print(f"Python version: {os.sys.version}") print(f"Working directory: {os.getcwd()}") print(f"HUB_REPO: {HUB_REPO}") print(f"Model available: {MODEL is not None}") print(f"Scaler available: {SCALER is not None}") print("="*50) main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402"""Gradio front-end for Fault_Classification_PMU_Data models.
The application loads a CNN-LSTM model (and accompanying scaler/metadata)produced by ``fault_classification_pmu.py`` and exposes a streamlinedprediction interface optimised for Hugging Face Spaces deployment. It supportsraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""
from __future__ import annotations
import jsonimport osimport shutil
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "-1")os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0")
import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import gradio as grimport joblibimport numpy as npimport pandas as pdimport requestsfrom huggingface_hub import hf_hub_downloadfrom tensorflow.keras.models import load_model
from fault_classification_pmu import ( DEFAULT_FEATURE_COLUMNS as TRAINING_DEFAULT_FEATURE_COLUMNS, LABEL_GUESS_CANDIDATES as TRAINING_LABEL_GUESSES, train_from_dataframe,)
# --------------------------------------------------------------------------------------# Configuration# --------------------------------------------------------------------------------------DEFAULT_FEATURE_COLUMNS: List[str] = list(TRAINING_DEFAULT_FEATURE_COLUMNS)DEFAULT_SEQUENCE_LENGTH = 32DEFAULT_STRIDE = 4
LOCAL_MODEL_FILE = os.environ.get("PMU_MODEL_FILE", "pmu_cnn_lstm_model.keras")LOCAL_SCALER_FILE = os.environ.get("PMU_SCALER_FILE", "pmu_feature_scaler.pkl")LOCAL_METADATA_FILE = os.environ.get("PMU_METADATA_FILE", "pmu_metadata.json")
MODEL_OUTPUT_DIR = Path(os.environ.get("PMU_MODEL_DIR", "model")).resolve()MODEL_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
HUB_REPO = os.environ.get("PMU_HUB_REPO", "")HUB_MODEL_FILENAME = os.environ.get("PMU_HUB_MODEL_FILENAME", LOCAL_MODEL_FILE)HUB_SCALER_FILENAME = os.environ.get("PMU_HUB_SCALER_FILENAME", LOCAL_SCALER_FILE)HUB_METADATA_FILENAME = os.environ.get("PMU_HUB_METADATA_FILENAME", LOCAL_METADATA_FILE)
ENV_MODEL_PATH = "PMU_MODEL_PATH"ENV_SCALER_PATH = "PMU_SCALER_PATH"ENV_METADATA_PATH = "PMU_METADATA_PATH"
# --------------------------------------------------------------------------------------# Utility functions for loading artifacts# --------------------------------------------------------------------------------------
def download_from_hub(filename: str) -> Optional[Path]: if not HUB_REPO or not filename: return None try: print(f"Downloading {filename} from {HUB_REPO} ...") # Add timeout to prevent hanging path = hf_hub_download(repo_id=HUB_REPO, filename=filename) print("Downloaded", path) return Path(path) except Exception as exc: # pragma: no cover - logging convenience print("Failed to download", filename, "from", HUB_REPO, ":", exc) print("Continuing without pre-trained model...") return None
def resolve_artifact( local_name: str, env_var: str, hub_filename: str) -> Optional[Path]: print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}") candidates = [Path(local_name)] if local_name else [] if local_name: candidates.append(MODEL_OUTPUT_DIR / Path(local_name).name) env_value = os.environ.get(env_var) if env_value: candidates.append(Path(env_value))
for candidate in candidates: if candidate and candidate.exists(): print(f"Found local artifact: {candidate}") return candidate
print(f"No local artifacts found, checking hub...") # Only try to download if we have a hub repo configured if HUB_REPO: return download_from_hub(hub_filename) else: print("No HUB_REPO configured, skipping download") return None
def load_metadata(path: Optional[Path]) -> Dict: if path and path.exists(): try: return json.loads(path.read_text()) except Exception as exc: # pragma: no cover - metadata parsing errors print("Failed to read metadata", path, exc) return {}
def try_load_scaler(path: Optional[Path]): if not path: return None try: scaler = joblib.load(path) print("Loaded scaler from", path) return scaler except Exception as exc: print("Failed to load scaler", path, exc) return None
# Initialize paths with error handlingprint("Starting application initialization...")try: MODEL_PATH = resolve_artifact(LOCAL_MODEL_FILE, ENV_MODEL_PATH, HUB_MODEL_FILENAME) print(f"Model path resolved: {MODEL_PATH}")except Exception as e: print(f"Model path resolution failed: {e}") MODEL_PATH = None
try: SCALER_PATH = resolve_artifact( LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME ) print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e: print(f"Scaler path resolution failed: {e}") SCALER_PATH = None
try: METADATA_PATH = resolve_artifact( LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME ) print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e: print(f"Metadata path resolution failed: {e}") METADATA_PATH = None
try: METADATA = load_metadata(METADATA_PATH) print(f"Metadata loaded: {len(METADATA)} entries")except Exception as e: print(f"Metadata loading failed: {e}") METADATA = {}
# Queuing configurationQUEUE_MAX_SIZE = 32# Apply a small per-event concurrency limit to avoid relying on the deprecated# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2
def try_load_model(path: Optional[Path], model_type: str, model_format: str): if not path: return None try: if model_type == "svm" or model_format == "joblib": model = joblib.load(path) else: model = load_model(path) print("Loaded model from", path) return model except Exception as exc: # pragma: no cover - runtime diagnostics print("Failed to load model", path, exc) return None
FEATURE_COLUMNS: List[str] = list(DEFAULT_FEATURE_COLUMNS)LABEL_CLASSES: List[str] = []LABEL_COLUMN: str = "Fault"SEQUENCE_LENGTH: int = DEFAULT_SEQUENCE_LENGTHDEFAULT_WINDOW_STRIDE: int = DEFAULT_STRIDEMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"
def _model_output_path(filename: str) -> str: return str(MODEL_OUTPUT_DIR / Path(filename).name)
MODEL_FILENAME_BY_TYPE: Dict[str, str] = { "cnn_lstm": Path(LOCAL_MODEL_FILE).name, "tcn": "pmu_tcn_model.keras", "svm": "pmu_svm_model.joblib",}
REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path( os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
TRAINING_DATA_REPO = os.environ.get( "PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)
GITHUB_CONTENT_CACHE: Dict[str, List[Dict[str, Any]]] = {}
APP_CSS = """#available-files-section { position: relative; display: flex; flex-direction: column; gap: 0.75rem; border-radius: 0.75rem;}
#available-files-grid { position: relative; overflow: visible;}
#available-files-grid .form { position: relative; min-height: 16rem;}
#available-files-section:has(.gradio-loading) { isolation: isolate;}
#available-files-grid .wrap { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.5rem; max-height: 24rem; min-height: 16rem; overflow-y: auto; padding-right: 0.25rem;}
#available-files-grid .wrap > div { min-width: 0;}
#available-files-grid .wrap label { margin: 0; display: flex; align-items: center; padding: 0.45rem 0.65rem; border-radius: 0.65rem; background-color: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease, border-color 0.2s ease; min-height: 2.5rem;}
#available-files-grid .wrap label:hover { background-color: rgba(90, 200, 250, 0.16); border-color: rgba(90, 200, 250, 0.4);}
#available-files-grid .wrap label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
#available-files-grid .gradio-loading { position: absolute; inset: 0; width: auto; height: auto; min-height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.72); border-radius: 0.75rem; z-index: 10; padding: 1.5rem; pointer-events: auto;}
#available-files-grid .gradio-loading > * { width: 100%;}
#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,#available-files-grid .gradio-loading [role="progressbar"],#available-files-grid .gradio-loading .wrap,#available-files-grid .gradio-loading .inner { width: 100% !important; max-width: none !important;}
#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label { text-align: center;}
#date-browser-row { gap: 0.75rem;}
#date-browser-row .date-browser-column { flex: 1 1 0%; min-width: 0;}
#date-browser-row .date-browser-column > .gradio-dropdown,#date-browser-row .date-browser-column > .gradio-button { width: 100%;}
#date-browser-row .date-browser-column > .gradio-dropdown > div { width: 100%;}
#date-browser-row .date-browser-column .gradio-button { justify-content: center;}
#training-files-summary textarea { max-height: 12rem; overflow-y: auto;}
#download-selected-button { width: 100%; position: relative; z-index: 0;}
#download-selected-button .gradio-button { width: 100%; justify-content: center;}
#artifact-download-row { gap: 0.75rem;}
#artifact-download-row .artifact-download-button { flex: 1 1 0%; min-width: 0;}
#artifact-download-row .artifact-download-button .gradio-button { width: 100%; justify-content: center;}"""
def _github_cache_key(path: str) -> str: return path or "__root__"
def _github_api_url(path: str) -> str: clean_path = path.strip("/") base = f"https://api.github.com/repos/{TRAINING_DATA_REPO}/contents" if clean_path: return f"{base}/{clean_path}?ref={TRAINING_DATA_BRANCH}" return f"{base}?ref={TRAINING_DATA_BRANCH}"
def list_remote_directory( path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]: key = _github_cache_key(path) if not force_refresh and key in GITHUB_CONTENT_CACHE: return GITHUB_CONTENT_CACHE[key]
url = _github_api_url(path) response = requests.get(url, timeout=30) if response.status_code != 200: raise RuntimeError( f"GitHub API request failed for `{path or '.'}` (status {response.status_code})." )
payload = response.json() if not isinstance(payload, list): raise RuntimeError( "Unexpected GitHub API payload. Expected a directory listing." )
GITHUB_CONTENT_CACHE[key] = payload return payload
def list_remote_years(force_refresh: bool = False) -> List[str]: entries = list_remote_directory("", force_refresh=force_refresh) years = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(years)
def list_remote_months(year: str, *, force_refresh: bool = False) -> List[str]: if not year: return [] entries = list_remote_directory(year, force_refresh=force_refresh) months = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(months)
def list_remote_days( year: str, month: str, *, force_refresh: bool = False) -> List[str]: if not year or not month: return [] entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh) days = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(days)
def list_remote_files( year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]: if not year or not month or not day: return [] entries = list_remote_directory( f"{year}/{month}/{day}", force_refresh=force_refresh ) files = [item["name"] for item in entries if item.get("type") == "file"] return sorted(files)
def download_repository_file(year: str, month: str, day: str, filename: str) -> Path: if not filename: raise ValueError("Filename cannot be empty when downloading repository data.")
relative_parts = [part for part in (year, month, day, filename) if part] if len(relative_parts) < 4: raise ValueError("Provide year, month, day, and filename to download a CSV.")
relative_path = "/".join(relative_parts) raw_url = ( f"https://raw.githubusercontent.com/{TRAINING_DATA_REPO}/" f"{TRAINING_DATA_BRANCH}/{relative_path}" )
response = requests.get(raw_url, stream=True, timeout=120) if response.status_code != 200: raise RuntimeError( f"Failed to download `{relative_path}` (status {response.status_code})." )
target_dir = TRAINING_DATA_DIR.joinpath(year, month, day) target_dir.mkdir(parents=True, exist_ok=True) target_path = target_dir / filename
with open(target_path, "wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): if chunk: handle.write(chunk)
return target_path
def _normalise_header(name: str) -> str: return str(name).strip().lower()
def guess_label_from_columns( columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]: if not columns: return preferred
lookup = {_normalise_header(col): str(col) for col in columns}
if preferred: preferred_stripped = preferred.strip() for col in columns: if str(col).strip() == preferred_stripped: return str(col) preferred_norm = _normalise_header(preferred) if preferred_norm in lookup: return lookup[preferred_norm]
for guess in TRAINING_LABEL_GUESSES: guess_norm = _normalise_header(guess) if guess_norm in lookup: return lookup[guess_norm]
for col in columns: if _normalise_header(col).startswith("fault"): return str(col)
return str(columns[0])
def summarise_training_files(paths: Sequence[str], notes: Sequence[str]) -> str: lines = [Path(path).name for path in paths] lines.extend(notes) return "\n".join(lines) if lines else "No training files available."
def read_training_status(status_file_path: str) -> str: """Read the current training status from file.""" try: if Path(status_file_path).exists(): with open(status_file_path, "r") as f: return f.read().strip() except Exception: pass return "Training status unavailable"
def _persist_uploaded_file(file_obj) -> Optional[Path]: if file_obj is None: return None
if isinstance(file_obj, (str, Path)): source = Path(file_obj) original_name = source.name else: source = Path(getattr(file_obj, "name", "") or getattr(file_obj, "path", "")) original_name = getattr(file_obj, "orig_name", source.name) or source.name if not source or not source.exists(): return None
original_name = Path(original_name).name or source.name
base_path = Path(original_name) destination = TRAINING_UPLOAD_DIR / base_path.name counter = 1 while destination.exists(): suffix = base_path.suffix or ".csv" destination = TRAINING_UPLOAD_DIR / f"{base_path.stem}_{counter}{suffix}" counter += 1
shutil.copy2(source, destination) return destination
def prepare_training_paths( paths: Sequence[str], current_label: str, cleanup_missing: bool = False): valid_paths: List[str] = [] notes: List[str] = [] columns_map: Dict[str, str] = {} for path in paths: try: df = load_measurement_csv(path) except Exception as exc: # pragma: no cover - user file diagnostics notes.append(f"⚠️ Skipped {Path(path).name}: {exc}") if cleanup_missing: try: Path(path).unlink(missing_ok=True) except Exception: pass continue valid_paths.append(str(path)) for col in df.columns: columns_map[_normalise_header(col)] = str(col)
summary = summarise_training_files(valid_paths, notes) preferred = current_label or LABEL_COLUMN dropdown_choices = ( sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN] ) guessed = guess_label_from_columns(dropdown_choices, preferred) dropdown_value = guessed or preferred or LABEL_COLUMN
return ( valid_paths, summary, gr.update(choices=dropdown_choices, value=dropdown_value), )
def append_training_files(new_files, existing_paths: Sequence[str], current_label: str): if isinstance(existing_paths, (str, Path)): paths: List[str] = [str(existing_paths)] elif existing_paths is None: paths = [] else: paths = list(existing_paths) if new_files: for file in new_files: persisted = _persist_uploaded_file(file) if persisted is None: continue path_str = str(persisted) if path_str not in paths: paths.append(path_str)
return prepare_training_paths(paths, current_label, cleanup_missing=True)
def load_repository_training_files(current_label: str, force_refresh: bool = False): if force_refresh: # Clearing the cache is enough because downloads are now on-demand. for cached in list(TRAINING_DATA_DIR.glob("*")): # On refresh we keep previously downloaded files; no deletion required. # The flag triggers downstream UI updates only. break
csv_paths = sorted( str(path) for path in TRAINING_DATA_DIR.rglob("*.csv") if path.is_file() ) if not csv_paths: message = ( "No local database CSVs are available yet. Use the database browser " "below to download specific days before training." ) default_label = current_label or LABEL_COLUMN or "Fault" return ( [], message, gr.update(choices=[default_label], value=default_label), message, )
valid_paths, summary, label_update = prepare_training_paths( csv_paths, current_label, cleanup_missing=False )
info = ( f"Ready with {len(valid_paths)} CSV file(s) cached locally under " f"the database cache `{TRAINING_DATA_DIR}`." )
return valid_paths, summary, label_update, info
def refresh_remote_browser(force_refresh: bool = False): if force_refresh: GITHUB_CONTENT_CACHE.clear() try: years = list_remote_years(force_refresh=force_refresh) if years: message = "Select a year, month, and day to list available CSV files." else: message = ( "⚠️ No directories were found in the database root. Verify the upstream " "structure." ) return ( gr.update(choices=years, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to query database: {exc}", )
def on_year_change(year: Optional[str]): if not year: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a year to continue.", ) try: months = list_remote_months(year) message = ( f"Year `{year}` selected. Choose a month to drill down." if months else f"⚠️ No months available under `{year}`." ) return ( gr.update(choices=months, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list months: {exc}", )
def on_month_change(year: Optional[str], month: Optional[str]): if not year or not month: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a month to continue.", ) try: days = list_remote_days(year, month) message = ( f"Month `{year}/{month}` ready. Pick a day to view files." if days else f"⚠️ No day folders found under `{year}/{month}`." ) return ( gr.update(choices=days, value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list days: {exc}", )
def on_day_change(year: Optional[str], month: Optional[str], day: Optional[str]): if not year or not month or not day: return ( gr.update(choices=[], value=[]), "Select a day to load file names.", ) try: files = list_remote_files(year, month, day) message = ( f"{len(files)} file(s) available for `{year}/{month}/{day}`." if files else f"⚠️ No CSV files found under `{year}/{month}/{day}`." ) return ( gr.update(choices=files, value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=[]), f"⚠️ Failed to list files: {exc}", )
def download_selected_files( year: Optional[str], month: Optional[str], day: Optional[str], filenames: Sequence[str], current_label: str,): if not filenames: message = "Select at least one CSV before downloading." local = load_repository_training_files(current_label) return (*local, gr.update(), message)
success: List[str] = [] notes: List[str] = [] for filename in filenames: try: path = download_repository_file( year or "", month or "", day or "", filename ) success.append(str(path)) except Exception as exc: notes.append(f"⚠️ {filename}: {exc}")
local = load_repository_training_files(current_label)
message_lines = [] if success: message_lines.append( f"Downloaded {len(success)} file(s) to the database cache `{TRAINING_DATA_DIR}`." ) if notes: message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_day_bundle( year: Optional[str], month: Optional[str], day: Optional[str], current_label: str,): if not (year and month and day): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year, month, and day before downloading an entire day.", )
try: files = list_remote_files(year, month, day) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to list CSVs for `{year}/{month}/{day}`: {exc}", )
if not files: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No CSV files were found for `{year}/{month}/{day}`.", )
result = list(download_selected_files(year, month, day, files, current_label)) result[-1] = ( f"Downloaded all {len(files)} CSV file(s) for `{year}/{month}/{day}`.\n" f"{result[-1]}" ) return tuple(result)
def download_month_bundle( year: Optional[str], month: Optional[str], current_label: str): if not (year and month): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year and month before downloading an entire month.", )
try: days = list_remote_days(year, month) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate days for `{year}/{month}`: {exc}", )
if not days: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No day folders were found for `{year}/{month}`.", )
downloaded = 0 notes: List[str] = [] for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}/{month}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_year_bundle(year: Optional[str], current_label: str): if not year: local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year before downloading an entire year of CSVs.", )
try: months = list_remote_months(year) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate months for `{year}`: {exc}", )
if not months: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No month folders were found for `{year}`.", )
downloaded = 0 notes: List[str] = [] for month in months: try: days = list_remote_days(year, month) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}`: {exc}") continue if not days: notes.append(f"⚠️ No day folders in `{year}/{month}`.") continue for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def clear_downloaded_cache(current_label: str): status_message = "" try: if TRAINING_DATA_DIR.exists(): shutil.rmtree(TRAINING_DATA_DIR) TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True) status_message = ( f"Cleared all downloaded CSVs from database cache `{TRAINING_DATA_DIR}`." ) except Exception as exc: status_message = f"⚠️ Failed to clear database cache: {exc}"
local = load_repository_training_files(current_label, force_refresh=True) remote = list(refresh_remote_browser(force_refresh=False)) if status_message: previous = remote[-1] if isinstance(previous, str) and previous: remote[-1] = f"{status_message}\n{previous}" else: remote[-1] = status_message
return (*local, *remote)
def normalise_output_directory(directory: Optional[str]) -> Path: base = Path(directory or MODEL_OUTPUT_DIR) base = base.expanduser() if not base.is_absolute(): base = (Path.cwd() / base).resolve() return base
def resolve_output_path( directory: Optional[Union[Path, str]], filename: Optional[str], fallback: str) -> Path: if isinstance(directory, Path): base = directory else: base = normalise_output_directory(directory) candidate = Path(filename or "").expanduser() if str(candidate): if candidate.is_absolute(): return candidate return (base / candidate).resolve() return (base / fallback).resolve()
ARTIFACT_FILE_EXTENSIONS: Tuple[str, ...] = ( ".keras", ".h5", ".joblib", ".pkl", ".json", ".onnx", ".zip", ".txt",)
def gather_directory_choices(current: Optional[str]) -> Tuple[List[str], str]: base = normalise_output_directory(current or str(MODEL_OUTPUT_DIR)) candidates = {str(base)} try: for candidate in base.parent.iterdir(): if candidate.is_dir(): candidates.add(str(candidate.resolve())) except Exception: pass return sorted(candidates), str(base)
def gather_artifact_choices( directory: Optional[str], selection: Optional[str] = None) -> Tuple[List[Tuple[str, str]], Optional[str]]: base = normalise_output_directory(directory) choices: List[Tuple[str, str]] = [] selected_value: Optional[str] = None if base.exists(): try: artifacts = sorted( [ path for path in base.iterdir() if path.is_file() and ( not ARTIFACT_FILE_EXTENSIONS or path.suffix.lower() in ARTIFACT_FILE_EXTENSIONS ) ], key=lambda path: path.name.lower(), ) choices = [(artifact.name, str(artifact)) for artifact in artifacts] except Exception: choices = []
if selection and any(value == selection for _, value in choices): selected_value = selection elif choices: selected_value = choices[0][1]
return choices, selected_value
def download_button_state(path: Optional[Union[str, Path]]): if not path: return gr.update(value=None, visible=False) candidate = Path(path) if candidate.exists(): return gr.update(value=str(candidate), visible=True) return gr.update(value=None, visible=False)
def clear_training_files(): default_label = LABEL_COLUMN or "Fault" for cached_file in TRAINING_UPLOAD_DIR.glob("*"): try: if cached_file.is_file(): cached_file.unlink(missing_ok=True) except Exception: pass return ( [], "No training files selected.", gr.update(choices=[default_label], value=default_label), gr.update(value=None), )
PROJECT_OVERVIEW_MD = """## Project Overview
This project focuses on classifying faults in electrical transmission lines andgrid-connected photovoltaic (PV) systems by combining ensemble learningtechniques with deep neural architectures.
## Datasets
### Transmission Line Fault Dataset- 134,406 samples collected from Phasor Measurement Units (PMUs)- 14 monitored channels covering currents, voltages, magnitudes, frequency, and phase angles- Labels span symmetrical and asymmetrical faults: NF, L-G, LL, LL-G, LLL, and LLL-G- Time span: 0 to 5.7 seconds with high-frequency sampling
### Grid-Connected PV System Fault Dataset- 2,163,480 samples from 16 experimental scenarios- 14 features including PV array measurements (Ipv, Vpv, Vdc), three-phase currents/voltages, aggregate magnitudes (Iabc, Vabc), and frequency indicators (If, Vf)- Captures array, inverter, grid anomaly, feedback sensor, and MPPT controller faults at 9.9989 μs sampling intervals
## Data Format Quick Reference
Each measurement file may be comma or tab separated and typically exposes thefollowing ordered columns:
1. `Timestamp`2. `[325] UPMU_SUB22:FREQ` – system frequency (Hz)3. `[326] UPMU_SUB22:DFDT` – frequency rate-of-change4. `[327] UPMU_SUB22:FLAG` – PMU status flag5. `[328] UPMU_SUB22-L1:MAG` – phase A voltage magnitude6. `[329] UPMU_SUB22-L1:ANG` – phase A voltage angle7. `[330] UPMU_SUB22-L2:MAG` – phase B voltage magnitude8. `[331] UPMU_SUB22-L2:ANG` – phase B voltage angle9. `[332] UPMU_SUB22-L3:MAG` – phase C voltage magnitude10. `[333] UPMU_SUB22-L3:ANG` – phase C voltage angle11. `[334] UPMU_SUB22-C1:MAG` – phase A current magnitude12. `[335] UPMU_SUB22-C1:ANG` – phase A current angle13. `[336] UPMU_SUB22-C2:MAG` – phase B current magnitude14. `[337] UPMU_SUB22-C2:ANG` – phase B current angle15. `[338] UPMU_SUB22-C3:MAG` – phase C current magnitude16. `[339] UPMU_SUB22-C3:ANG` – phase C current angle
The training tab automatically downloads the latest CSV exports from the`VincentCroft/ThesisModelData` repository and concatenates them before buildingsliding windows.
## Models Developed
1. **Support Vector Machine (SVM)** – provides the classical machine learning baseline with balanced accuracy across both datasets (85% PMU / 83% PV).2. **CNN-LSTM** – couples convolutional feature extraction with temporal memory, achieving 92% PMU / 89% PV accuracy.3. **Temporal Convolutional Network (TCN)** – leverages dilated convolutions for long-range context and delivers the best trade-off between accuracy and training time (94% PMU / 91% PV).
## Results Summary
- **Transmission Line Fault Classification**: SVM 85%, CNN-LSTM 92%, TCN 94%- **PV System Fault Classification**: SVM 83%, CNN-LSTM 89%, TCN 91%
Use the **Inference** tab to score new PMU/PV windows and the **Training** tab tofine-tune or retrain any of the supported models directly within Hugging FaceSpaces. The logs panel will surface TensorBoard archives whenever deep-learningmodels are trained."""
def load_measurement_csv(path: str) -> pd.DataFrame: """Read a PMU/PV measurement file with flexible separators and column mapping."""
try: df = pd.read_csv(path, sep=None, engine="python", encoding="utf-8-sig") except Exception: df = None for separator in ("\t", ",", ";"): try: df = pd.read_csv( path, sep=separator, engine="python", encoding="utf-8-sig" ) break except Exception: df = None if df is None: raise
# Clean column names df.columns = [str(col).strip() for col in df.columns]
print(f"Loaded CSV with {len(df)} rows and {len(df.columns)} columns") print(f"Columns: {list(df.columns)}") print(f"Data shape: {df.shape}")
# Check if we have enough data for training if len(df) < 100: print( f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training." )
# Check for label column has_label = any( col.lower() in ["fault", "label", "class", "target"] for col in df.columns ) if not has_label: print( "Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples." ) df["Fault"] = "Normal" # Add dummy label for training
# Create column mapping - map similar column names to expected format column_mapping = {} expected_cols = list(REQUIRED_PMU_COLUMNS)
# If we have at least the right number of numeric columns after Timestamp, use positional mapping if "Timestamp" in df.columns: numeric_cols = [col for col in df.columns if col != "Timestamp"] if len(numeric_cols) >= len(expected_cols): # Map by position (after Timestamp) for i, expected_col in enumerate(expected_cols): if i < len(numeric_cols): column_mapping[numeric_cols[i]] = expected_col
# Rename columns to match expected format df = df.rename(columns=column_mapping)
# Check if we have the required columns after mapping missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns] if missing: # If still missing, try a more flexible approach available_numeric = df.select_dtypes(include=[np.number]).columns.tolist() if len(available_numeric) >= len(expected_cols): # Use the first N numeric columns for i, expected_col in enumerate(expected_cols): if i < len(available_numeric): if available_numeric[i] not in df.columns: continue df = df.rename(columns={available_numeric[i]: expected_col})
# Recheck missing columns missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns]
if missing: missing_str = ", ".join(missing) available_str = ", ".join(df.columns.tolist()) raise ValueError( f"Missing required PMU feature columns: {missing_str}. " f"Available columns: {available_str}. " "Please ensure your CSV has the correct format with Timestamp followed by PMU measurements." )
return df
def apply_metadata(metadata: Dict[str, Any]) -> None: global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMAT FEATURE_COLUMNS = [ str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS) ] LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])] LABEL_COLUMN = str(metadata.get("label_column", "Fault")) SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH)) DEFAULT_WINDOW_STRIDE = int(metadata.get("stride", DEFAULT_STRIDE)) MODEL_TYPE = str(metadata.get("model_type", "cnn_lstm")).lower() MODEL_FORMAT = str( metadata.get("model_format", "joblib" if MODEL_TYPE == "svm" else "keras") ).lower()
apply_metadata(METADATA)
def sync_label_classes_from_model(model: Optional[object]) -> None: global LABEL_CLASSES if model is None: return if hasattr(model, "classes_"): LABEL_CLASSES = [str(label) for label in getattr(model, "classes_")] elif not LABEL_CLASSES and hasattr(model, "output_shape"): LABEL_CLASSES = [str(i) for i in range(int(model.output_shape[-1]))]
# Load model and scaler with error handlingprint("Loading model and scaler...")try: MODEL = try_load_model(MODEL_PATH, MODEL_TYPE, MODEL_FORMAT) print(f"Model loaded: {MODEL is not None}")except Exception as e: print(f"Model loading failed: {e}") MODEL = None
try: SCALER = try_load_scaler(SCALER_PATH) print(f"Scaler loaded: {SCALER is not None}")except Exception as e: print(f"Scaler loading failed: {e}") SCALER = None
try: sync_label_classes_from_model(MODEL) print("Label classes synchronized")except Exception as e: print(f"Label sync failed: {e}")
print("Application initialization completed.")print( f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")
def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None: global MODEL_PATH, SCALER_PATH, METADATA_PATH, MODEL, SCALER, METADATA MODEL_PATH = model_path SCALER_PATH = scaler_path METADATA_PATH = metadata_path METADATA = load_metadata(metadata_path) apply_metadata(METADATA) MODEL = try_load_model(model_path, MODEL_TYPE, MODEL_FORMAT) SCALER = try_load_scaler(scaler_path) sync_label_classes_from_model(MODEL)
# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------
def ensure_ready(): if MODEL is None or SCALER is None: raise RuntimeError( "The model and feature scaler are not available. Upload the trained model " "(for example `pmu_cnn_lstm_model.keras`, `pmu_tcn_model.keras`, or `pmu_svm_model.joblib`), " "the feature scaler (`pmu_feature_scaler.pkl`), and the metadata JSON (`pmu_metadata.json`) to the Space root " "or configure the Hugging Face Hub environment variables so the artifacts can be downloaded " "automatically." )
def parse_text_features(text: str) -> np.ndarray: cleaned = re.sub(r"[;\n\t]+", ",", text.strip()) arr = np.fromstring(cleaned, sep=",") if arr.size == 0: raise ValueError( "No feature values were parsed. Please enter comma-separated numbers." ) return arr.astype(np.float32)
def apply_scaler(sequences: np.ndarray) -> np.ndarray: if SCALER is None: return sequences shape = sequences.shape flattened = sequences.reshape(-1, shape[-1]) scaled = SCALER.transform(flattened) return scaled.reshape(shape)
def make_sliding_windows( data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray: if data.shape[0] < sequence_length: raise ValueError( f"The dataset contains {data.shape[0]} rows which is less than the requested sequence " f"length {sequence_length}. Provide more samples or reduce the sequence length." ) windows = [ data[start : start + sequence_length] for start in range(0, data.shape[0] - sequence_length + 1, stride) ] return np.stack(windows)
def dataframe_to_sequences( df: pd.DataFrame, *, sequence_length: int, stride: int, feature_columns: Sequence[str], drop_label: bool = True,) -> np.ndarray: work_df = df.copy() if drop_label and LABEL_COLUMN in work_df.columns: work_df = work_df.drop(columns=[LABEL_COLUMN]) if "Timestamp" in work_df.columns: work_df = work_df.sort_values("Timestamp")
available_cols = [c for c in feature_columns if c in work_df.columns] n_features = len(feature_columns) if available_cols and len(available_cols) == n_features: array = work_df[available_cols].astype(np.float32).to_numpy() return make_sliding_windows(array, sequence_length, stride)
numeric_df = work_df.select_dtypes(include=[np.number]) array = numeric_df.astype(np.float32).to_numpy() if array.shape[1] == n_features * sequence_length: return array.reshape(array.shape[0], sequence_length, n_features) if sequence_length == 1 and array.shape[1] == n_features: return array.reshape(array.shape[0], 1, n_features) raise ValueError( "CSV columns do not match the expected feature layout. Include the full PMU feature set " "or provide pre-shaped sliding window data." )
def label_name(index: int) -> str: if 0 <= index < len(LABEL_CLASSES): return str(LABEL_CLASSES[index]) return f"class_{index}"
def format_predictions(probabilities: np.ndarray) -> pd.DataFrame: rows: List[Dict[str, object]] = [] order = np.argsort(probabilities, axis=1)[:, ::-1] for idx, (prob_row, ranking) in enumerate(zip(probabilities, order)): top_idx = int(ranking[0]) top_label = label_name(top_idx) top_conf = float(prob_row[top_idx]) top3 = [f"{label_name(i)} ({prob_row[i]*100:.2f}%)" for i in ranking[:3]] rows.append( { "window": idx, "predicted_label": top_label, "confidence": round(top_conf, 4), "top3": " | ".join(top3), } ) return pd.DataFrame(rows)
def probabilities_to_json(probabilities: np.ndarray) -> List[Dict[str, object]]: payload: List[Dict[str, object]] = [] for idx, prob_row in enumerate(probabilities): payload.append( { "window": int(idx), "probabilities": { label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0]) }, } ) return payload
def predict_sequences( sequences: np.ndarray,) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: ensure_ready() sequences = apply_scaler(sequences.astype(np.float32)) if MODEL_TYPE == "svm": flattened = sequences.reshape(sequences.shape[0], -1) if hasattr(MODEL, "predict_proba"): probs = MODEL.predict_proba(flattened) else: raise RuntimeError( "Loaded SVM model does not expose predict_proba. Retrain with probability=True." ) else: probs = MODEL.predict(sequences, verbose=0) table = format_predictions(probs) json_probs = probabilities_to_json(probs) architecture = MODEL_TYPE.replace("_", "-").upper() status = f"Generated {len(sequences)} windows. {architecture} model output dimension: {probs.shape[1]}." return status, table, json_probs
def predict_from_text( text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: arr = parse_text_features(text) n_features = len(FEATURE_COLUMNS) if arr.size % n_features != 0: raise ValueError( f"The number of values ({arr.size}) is not a multiple of the feature dimension " f"({n_features}). Provide values in groups of {n_features}." ) timesteps = arr.size // n_features if timesteps != sequence_length: raise ValueError( f"Detected {timesteps} timesteps which does not match the configured sequence length " f"({sequence_length})." ) sequences = arr.reshape(1, sequence_length, n_features) status, table, probs = predict_sequences(sequences) status = f"Single window prediction complete. {status}" return status, table, probs
def predict_from_csv( file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: df = load_measurement_csv(file_obj.name) sequences = dataframe_to_sequences( df, sequence_length=sequence_length, stride=stride, feature_columns=FEATURE_COLUMNS, ) status, table, probs = predict_sequences(sequences) status = f"CSV processed successfully. Generated {len(sequences)} windows. {status}" return status, table, probs
# --------------------------------------------------------------------------------------# Training helpers# --------------------------------------------------------------------------------------
def classification_report_to_dataframe(report: Dict[str, Any]) -> pd.DataFrame: rows: List[Dict[str, Any]] = [] for label, metrics in report.items(): if isinstance(metrics, dict): row = {"label": label} for key, value in metrics.items(): if key == "support": row[key] = int(value) else: row[key] = round(float(value), 4) rows.append(row) else: rows.append({"label": label, "accuracy": round(float(metrics), 4)}) return pd.DataFrame(rows)
def confusion_matrix_to_dataframe( confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame: if not confusion: return pd.DataFrame() df = pd.DataFrame(confusion, index=list(labels), columns=list(labels)) df.index.name = "True Label" df.columns.name = "Predicted Label" return df
# --------------------------------------------------------------------------------------# Gradio interface# --------------------------------------------------------------------------------------
def build_interface() -> gr.Blocks: theme = gr.themes.Soft( primary_hue="sky", secondary_hue="blue", neutral_hue="gray" ).set( body_background_fill="#1f1f1f", body_text_color="#f5f5f5", block_background_fill="#262626", block_border_color="#333333", button_primary_background_fill="#5ac8fa", button_primary_background_fill_hover="#48b5eb", button_primary_border_color="#38bdf8", button_primary_text_color="#0f172a", button_secondary_background_fill="#3f3f46", button_secondary_text_color="#f5f5f5", )
def _normalise_directory_string(value: Optional[Union[str, Path]]) -> str: if value is None: return "" path = Path(value).expanduser() try: return str(path.resolve()) except Exception: return str(path)
with gr.Blocks( title="Fault Classification - PMU Data", theme=theme, css=APP_CSS ) as demo: gr.Markdown("# Fault Classification for PMU & PV Data") gr.Markdown( "🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers." ) if MODEL is None or SCALER is None: gr.Markdown( "⚠️ **Artifacts Missing** — Upload `pmu_cnn_lstm_model.keras`, " "`pmu_feature_scaler.pkl`, and `pmu_metadata.json` to enable inference, " "or configure the Hugging Face Hub environment variables so they can be downloaded." ) else: class_count = len(LABEL_CLASSES) if LABEL_CLASSES else "unknown" gr.Markdown( f"Loaded a **{MODEL_TYPE.upper()}** model ({MODEL_FORMAT.upper()}) with " f"{len(FEATURE_COLUMNS)} features, sequence length **{SEQUENCE_LENGTH}**, and " f"{class_count} target classes. Use the tabs below to run inference or fine-tune " "the model with your own CSV files." )
with gr.Accordion("Feature Reference", open=False): gr.Markdown( f"Each time window expects **{len(FEATURE_COLUMNS)} features** ordered as follows:\n" + "\n".join(f"- {name}" for name in FEATURE_COLUMNS) ) gr.Markdown( f"Default training parameters: **sequence length = {SEQUENCE_LENGTH}**, " f"**stride = {DEFAULT_WINDOW_STRIDE}**. Adjust them in the tabs as needed." )
with gr.Tabs(): with gr.Tab("Overview"): gr.Markdown(PROJECT_OVERVIEW_MD) with gr.Tab("Inference"): gr.Markdown("## Run Inference") with gr.Row(): file_in = gr.File(label="Upload PMU CSV", file_types=[".csv"]) text_in = gr.Textbox( lines=4, label="Or paste a single window (comma separated)", placeholder="49.97772,1.215825E-38,...", )
with gr.Row(): sequence_length_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length (timesteps)", ) stride_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="CSV window stride", )
predict_btn = gr.Button("🚀 Run Inference", variant="primary") status_out = gr.Textbox(label="Status", interactive=False) table_out = gr.Dataframe( headers=["window", "predicted_label", "confidence", "top3"], label="Predictions", interactive=False, ) probs_out = gr.JSON(label="Per-window probabilities")
def _run_prediction(file_obj, text, sequence_length, stride): sequence_length = int(sequence_length) stride = int(stride) try: if file_obj is not None: return predict_from_csv(file_obj, sequence_length, stride) if text and text.strip(): return predict_from_text(text, sequence_length) return ( "Please upload a CSV file or provide feature values.", pd.DataFrame(), [], ) except Exception as exc: return f"Prediction failed: {exc}", pd.DataFrame(), []
predict_btn.click( _run_prediction, inputs=[file_in, text_in, sequence_length_input, stride_input], outputs=[status_out, table_out, probs_out], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Tab("Training"): gr.Markdown("## Train or Fine-tune the Model") gr.Markdown( "Training data is automatically downloaded from the database. " "Refresh the cache if new files are added upstream." )
training_files_state = gr.State([]) with gr.Row(): with gr.Column(scale=3): training_files_summary = gr.Textbox( label="Database training CSVs", value="Training dataset not loaded yet.", lines=4, interactive=False, elem_id="training-files-summary", ) with gr.Column(scale=2, min_width=240): dataset_info = gr.Markdown( "No local database CSVs downloaded yet.", ) dataset_refresh = gr.Button( "🔄 Reload dataset from database", variant="secondary", ) clear_cache_button = gr.Button( "🧹 Clear downloaded cache", variant="secondary", )
with gr.Accordion("📂 DataBaseBrowser", open=False): gr.Markdown( "Browse the upstream database by date and download only the CSVs you need." ) with gr.Row(elem_id="date-browser-row"): with gr.Column(scale=1, elem_classes=["date-browser-column"]): year_selector = gr.Dropdown(label="Year", choices=[]) year_download_button = gr.Button( "⬇️ Download year CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): month_selector = gr.Dropdown(label="Month", choices=[]) month_download_button = gr.Button( "⬇️ Download month CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): day_selector = gr.Dropdown(label="Day", choices=[]) day_download_button = gr.Button( "⬇️ Download day CSVs", variant="secondary" ) with gr.Column(elem_id="available-files-section"): available_files = gr.CheckboxGroup( label="Available CSV files", choices=[], value=[], elem_id="available-files-grid", ) download_button = gr.Button( "⬇️ Download selected CSVs", variant="secondary", elem_id="download-selected-button", ) repo_status = gr.Markdown( "Click 'Reload dataset from database' to fetch the directory tree." )
with gr.Row(): label_input = gr.Dropdown( value=LABEL_COLUMN, choices=[LABEL_COLUMN], allow_custom_value=True, label="Label column name", ) model_selector = gr.Radio( choices=["CNN-LSTM", "TCN", "SVM"], value=( "TCN" if MODEL_TYPE == "tcn" else ("SVM" if MODEL_TYPE == "svm" else "CNN-LSTM") ), label="Model architecture", ) sequence_length_train = gr.Slider( minimum=4, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length", ) stride_train = gr.Slider( minimum=1, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="Stride", )
model_default = MODEL_FILENAME_BY_TYPE.get( MODEL_TYPE, Path(LOCAL_MODEL_FILE).name )
with gr.Row(): validation_train = gr.Slider( minimum=0.05, maximum=0.4, step=0.05, value=0.2, label="Validation split", ) batch_train = gr.Slider( minimum=32, maximum=512, step=32, value=128, label="Batch size", ) epochs_train = gr.Slider( minimum=5, maximum=100, step=5, value=50, label="Epochs", )
directory_choices, directory_default = gather_directory_choices( str(MODEL_OUTPUT_DIR) ) artifact_choices, default_artifact = gather_artifact_choices( directory_default )
with gr.Row(): output_directory = gr.Dropdown( value=directory_default, label="Output directory", choices=directory_choices, allow_custom_value=True, ) model_name = gr.Textbox( value=model_default, label="Model output filename", ) scaler_name = gr.Textbox( value=Path(LOCAL_SCALER_FILE).name, label="Scaler output filename", ) metadata_name = gr.Textbox( value=Path(LOCAL_METADATA_FILE).name, label="Metadata output filename", )
with gr.Row(): artifact_browser = gr.Dropdown( label="Saved artifacts in directory", choices=artifact_choices, value=default_artifact, ) artifact_download_button = gr.DownloadButton( "⬇️ Download selected artifact", value=default_artifact, visible=bool(default_artifact), variant="secondary", )
def on_output_directory_change(selected_dir, current_selection): choices, normalised = gather_directory_choices(selected_dir) artifact_options, selected = gather_artifact_choices( normalised, current_selection ) return ( gr.update(choices=choices, value=normalised), gr.update(choices=artifact_options, value=selected), download_button_state(selected), )
def on_artifact_change(selected_path): return download_button_state(selected_path)
output_directory.change( on_output_directory_change, inputs=[output_directory, artifact_browser], outputs=[ output_directory, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
artifact_browser.change( on_artifact_change, inputs=[artifact_browser], outputs=[artifact_download_button], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Row(elem_id="artifact-download-row"): model_download_button = gr.DownloadButton( "⬇️ Download model file", value=None, visible=False, elem_classes=["artifact-download-button"], ) scaler_download_button = gr.DownloadButton( "⬇️ Download scaler file", value=None, visible=False, elem_classes=["artifact-download-button"], ) metadata_download_button = gr.DownloadButton( "⬇️ Download metadata file", value=None, visible=False, elem_classes=["artifact-download-button"], ) tensorboard_download_button = gr.DownloadButton( "⬇️ Download TensorBoard logs", value=None, visible=False, elem_classes=["artifact-download-button"], )
model_download_button.file_name = Path(LOCAL_MODEL_FILE).name scaler_download_button.file_name = Path(LOCAL_SCALER_FILE).name metadata_download_button.file_name = Path(LOCAL_METADATA_FILE).name tensorboard_download_button.file_name = "tensorboard_logs.zip"
tensorboard_toggle = gr.Checkbox( value=True, label="Enable TensorBoard logging (creates downloadable archive)", )
def _suggest_model_filename(choice: str, current_value: str): choice_key = (choice or "cnn_lstm").lower().replace("-", "_") suggested = MODEL_FILENAME_BY_TYPE.get( choice_key, Path(LOCAL_MODEL_FILE).name ) known_defaults = set(MODEL_FILENAME_BY_TYPE.values()) current_name = Path(current_value).name if current_value else "" if current_name and current_name not in known_defaults: return gr.update() return gr.update(value=suggested)
model_selector.change( _suggest_model_filename, inputs=[model_selector, model_name], outputs=model_name, )
with gr.Row(): train_button = gr.Button("🛠️ Start Training", variant="primary") progress_button = gr.Button( "📊 Check Progress", variant="secondary" )
# Training status display training_status = gr.Textbox(label="Training Status", interactive=False) report_output = gr.Dataframe( label="Classification report", interactive=False ) history_output = gr.JSON(label="Training history") confusion_output = gr.Dataframe( label="Confusion matrix", interactive=False )
# Message area at the bottom for progress updates with gr.Accordion("📋 Progress Messages", open=True): progress_messages = gr.Textbox( label="Training Messages", lines=8, max_lines=20, interactive=False, autoscroll=True, placeholder="Click 'Check Progress' to see training updates...", ) with gr.Row(): gr.Button("🗑️ Clear Messages", variant="secondary").click( lambda: "", outputs=[progress_messages] )
def _run_training( file_paths, label_column, model_choice, sequence_length, stride, validation_split, batch_size, epochs, output_dir, model_filename, scaler_filename, metadata_filename, enable_tensorboard, ): base_dir = normalise_output_directory(output_dir) try: base_dir.mkdir(parents=True, exist_ok=True)
model_path = resolve_output_path( base_dir, model_filename, Path(LOCAL_MODEL_FILE).name, ) scaler_path = resolve_output_path( base_dir, scaler_filename, Path(LOCAL_SCALER_FILE).name, ) metadata_path = resolve_output_path( base_dir, metadata_filename, Path(LOCAL_METADATA_FILE).name, )
model_path.parent.mkdir(parents=True, exist_ok=True) scaler_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True)
# Create status file path for progress tracking status_file = model_path.parent / "training_status.txt"
# Initialize status with open(status_file, "w") as f: f.write("Starting training setup...")
if not file_paths: raise ValueError( "No training CSVs were found in the database cache. " "Use 'Reload dataset from database' and try again." )
with open(status_file, "w") as f: f.write("Loading and validating CSV files...")
available_paths = [ path for path in file_paths if Path(path).exists() ] missing_paths = [ Path(path).name for path in file_paths if not Path(path).exists() ] if not available_paths: raise ValueError( "Database training dataset is unavailable. Reload the dataset and retry." )
dfs = [load_measurement_csv(path) for path in available_paths] combined = pd.concat(dfs, ignore_index=True)
# Validate data size and provide recommendations total_samples = len(combined) if total_samples < 100: print( f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results." ) print( "Automatically switching to SVM for small dataset compatibility." ) if model_choice in ["cnn_lstm", "tcn"]: model_choice = "svm" print( f"Model type changed to SVM for better small dataset performance." ) if total_samples < 10: raise ValueError( f"Insufficient data: {total_samples} samples. Need at least 10 samples for training." )
label_column = (label_column or LABEL_COLUMN).strip() if not label_column: raise ValueError("Label column name cannot be empty.")
model_choice = ( (model_choice or "CNN-LSTM").lower().replace("-", "_") ) if model_choice not in {"cnn_lstm", "tcn", "svm"}: raise ValueError( "Select CNN-LSTM, TCN, or SVM for the model architecture." )
with open(status_file, "w") as f: f.write( f"Starting {model_choice.upper()} training with {len(combined)} samples..." )
# Start training result = train_from_dataframe( combined, label_column=label_column, feature_columns=None, sequence_length=int(sequence_length), stride=int(stride), validation_split=float(validation_split), batch_size=int(batch_size), epochs=int(epochs), model_type=model_choice, model_path=model_path, scaler_path=scaler_path, metadata_path=metadata_path, enable_tensorboard=bool(enable_tensorboard), )
refresh_artifacts( Path(result["model_path"]), Path(result["scaler_path"]), Path(result["metadata_path"]), )
report_df = classification_report_to_dataframe( result["classification_report"] ) confusion_df = confusion_matrix_to_dataframe( result["confusion_matrix"], result["class_names"] ) tensorboard_dir = result.get("tensorboard_log_dir") tensorboard_zip = result.get("tensorboard_zip_path")
architecture = result["model_type"].replace("_", "-").upper() status = ( f"Training complete using a {architecture} architecture. " f"{result['num_sequences']} windows derived from " f"{result['num_samples']} rows across {len(available_paths)} file(s)." f" Artifacts saved to:" f"\n• Model: {result['model_path']}\n" f"• Scaler: {result['scaler_path']}\n" f"• Metadata: {result['metadata_path']}" )
status += f"\nLabel column used: {result.get('label_column', label_column)}"
if tensorboard_dir: status += ( f"\nTensorBoard logs directory: {tensorboard_dir}" f'\nRun `tensorboard --logdir "{tensorboard_dir}"` to inspect the training curves.' "\nDownload the archive below to explore the run offline." )
if missing_paths: skipped = ", ".join(missing_paths) status = f"⚠️ Skipped missing files: {skipped}\n" + status
artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir), result["model_path"] )
return ( status, report_df, result["history"], confusion_df, download_button_state(result["model_path"]), download_button_state(result["scaler_path"]), download_button_state(result["metadata_path"]), download_button_state(tensorboard_zip), gr.update(value=result.get("label_column", label_column)), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), ) except Exception as exc: artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir) ) return ( f"Training failed: {exc}", pd.DataFrame(), {}, pd.DataFrame(), download_button_state(None), download_button_state(None), download_button_state(None), download_button_state(None), gr.update(), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), )
def _check_progress(output_dir, model_filename, current_messages): """Check training progress by reading status file and accumulate messages.""" model_path = resolve_output_path( output_dir, model_filename, Path(LOCAL_MODEL_FILE).name ) status_file = model_path.parent / "training_status.txt" status_message = read_training_status(str(status_file))
# Add timestamp to the message from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S") new_message = f"[{timestamp}] {status_message}"
# Accumulate messages, keeping last 50 lines to prevent overflow if current_messages: lines = current_messages.split("\n") lines.append(new_message) # Keep only last 50 lines if len(lines) > 50: lines = lines[-50:] accumulated_messages = "\n".join(lines) else: accumulated_messages = new_message
return accumulated_messages
train_button.click( _run_training, inputs=[ training_files_state, label_input, model_selector, sequence_length_train, stride_train, validation_train, batch_train, epochs_train, output_directory, model_name, scaler_name, metadata_name, tensorboard_toggle, ], outputs=[ training_status, report_output, history_output, confusion_output, model_download_button, scaler_download_button, metadata_download_button, tensorboard_download_button, label_input, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
progress_button.click( _check_progress, inputs=[output_directory, model_name, progress_messages], outputs=[progress_messages], )
year_selector.change( on_year_change, inputs=[year_selector], outputs=[ month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_selector.change( on_month_change, inputs=[year_selector, month_selector], outputs=[day_selector, available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_selector.change( on_day_change, inputs=[year_selector, month_selector, day_selector], outputs=[available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
download_button.click( download_selected_files, inputs=[ year_selector, month_selector, day_selector, available_files, label_input, ], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
year_download_button.click( download_year_bundle, inputs=[year_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_download_button.click( download_month_bundle, inputs=[year_selector, month_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_download_button.click( download_day_bundle, inputs=[year_selector, month_selector, day_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _reload_dataset(current_label): local = load_repository_training_files( current_label, force_refresh=True ) remote = refresh_remote_browser(force_refresh=True) return (*local, *remote)
dataset_refresh.click( _reload_dataset, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
clear_cache_button.click( clear_downloaded_cache, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _initialise_dataset(): local = load_repository_training_files( LABEL_COLUMN, force_refresh=False ) remote = refresh_remote_browser(force_refresh=False) return (*local, *remote)
demo.load( _initialise_dataset, inputs=None, outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], queue=False, )
return demo
# --------------------------------------------------------------------------------------# Launch helpers# --------------------------------------------------------------------------------------
def resolve_server_port() -> int: for env_var in ("PORT", "GRADIO_SERVER_PORT"): value = os.environ.get(env_var) if value: try: return int(value) except ValueError: print(f"Ignoring invalid port value from {env_var}: {value}") return 7860
def main(): print("Building Gradio interface...") try: demo = build_interface() print("Interface built successfully") except Exception as e: print(f"Failed to build interface: {e}") import traceback
traceback.print_exc() return
print("Setting up queue...") try: demo.queue(max_size=QUEUE_MAX_SIZE) print("Queue configured") except Exception as e: print(f"Failed to configure queue: {e}")
try: port = resolve_server_port() print(f"Launching Gradio app on port {port}") demo.launch(server_name="0.0.0.0", server_port=port, show_error=True) except OSError as exc: print("Failed to launch on requested port:", exc) try: demo.launch(server_name="0.0.0.0", show_error=True) except Exception as e: print(f"Failed to launch completely: {e}") except Exception as e: print(f"Unexpected launch error: {e}") import traceback
traceback.print_exc()
if __name__ == "__main__": print("=" * 50) print("PMU Fault Classification App Starting") print(f"Python version: {os.sys.version}") print(f"Working directory: {os.getcwd()}") print(f"HUB_REPO: {HUB_REPO}") print(f"Model available: {MODEL is not None}") print(f"Scaler available: {SCALER is not None}") print("=" * 50) main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402"""Gradio front-end for Fault_Classification_PMU_Data models.
The application loads a CNN-LSTM model (and accompanying scaler/metadata)produced by ``fault_classification_pmu.py`` and exposes a streamlinedprediction interface optimised for Hugging Face Spaces deployment. It supportsraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""
from __future__ import annotations
import jsonimport osimport shutil
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "-1")os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0")
import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import gradio as grimport joblibimport numpy as npimport pandas as pdimport requestsfrom huggingface_hub import hf_hub_downloadfrom tensorflow.keras.models import load_model
from fault_classification_pmu import ( DEFAULT_FEATURE_COLUMNS as TRAINING_DEFAULT_FEATURE_COLUMNS, LABEL_GUESS_CANDIDATES as TRAINING_LABEL_GUESSES, train_from_dataframe,)
# --------------------------------------------------------------------------------------# Configuration# --------------------------------------------------------------------------------------DEFAULT_FEATURE_COLUMNS: List[str] = list(TRAINING_DEFAULT_FEATURE_COLUMNS)DEFAULT_SEQUENCE_LENGTH = 32DEFAULT_STRIDE = 4
LOCAL_MODEL_FILE = os.environ.get("PMU_MODEL_FILE", "pmu_cnn_lstm_model.keras")LOCAL_SCALER_FILE = os.environ.get("PMU_SCALER_FILE", "pmu_feature_scaler.pkl")LOCAL_METADATA_FILE = os.environ.get("PMU_METADATA_FILE", "pmu_metadata.json")
MODEL_OUTPUT_DIR = Path(os.environ.get("PMU_MODEL_DIR", "model")).resolve()MODEL_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
HUB_REPO = os.environ.get("PMU_HUB_REPO", "")HUB_MODEL_FILENAME = os.environ.get("PMU_HUB_MODEL_FILENAME", LOCAL_MODEL_FILE)HUB_SCALER_FILENAME = os.environ.get("PMU_HUB_SCALER_FILENAME", LOCAL_SCALER_FILE)HUB_METADATA_FILENAME = os.environ.get("PMU_HUB_METADATA_FILENAME", LOCAL_METADATA_FILE)
ENV_MODEL_PATH = "PMU_MODEL_PATH"ENV_SCALER_PATH = "PMU_SCALER_PATH"ENV_METADATA_PATH = "PMU_METADATA_PATH"
# --------------------------------------------------------------------------------------# Utility functions for loading artifacts# --------------------------------------------------------------------------------------
def download_from_hub(filename: str) -> Optional[Path]: if not HUB_REPO or not filename: return None try: print(f"Downloading {filename} from {HUB_REPO} ...") # Add timeout to prevent hanging path = hf_hub_download(repo_id=HUB_REPO, filename=filename) print("Downloaded", path) return Path(path) except Exception as exc: # pragma: no cover - logging convenience print("Failed to download", filename, "from", HUB_REPO, ":", exc) print("Continuing without pre-trained model...") return None
def resolve_artifact( local_name: str, env_var: str, hub_filename: str) -> Optional[Path]: print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}") candidates = [Path(local_name)] if local_name else [] if local_name: candidates.append(MODEL_OUTPUT_DIR / Path(local_name).name) env_value = os.environ.get(env_var) if env_value: candidates.append(Path(env_value))
for candidate in candidates: if candidate and candidate.exists(): print(f"Found local artifact: {candidate}") return candidate
print(f"No local artifacts found, checking hub...") # Only try to download if we have a hub repo configured if HUB_REPO: return download_from_hub(hub_filename) else: print("No HUB_REPO configured, skipping download") return None
def load_metadata(path: Optional[Path]) -> Dict: if path and path.exists(): try: return json.loads(path.read_text()) except Exception as exc: # pragma: no cover - metadata parsing errors print("Failed to read metadata", path, exc) return {}
def try_load_scaler(path: Optional[Path]): if not path: return None try: scaler = joblib.load(path) print("Loaded scaler from", path) return scaler except Exception as exc: print("Failed to load scaler", path, exc) return None
# Initialize paths with error handlingprint("Starting application initialization...")try: MODEL_PATH = resolve_artifact(LOCAL_MODEL_FILE, ENV_MODEL_PATH, HUB_MODEL_FILENAME) print(f"Model path resolved: {MODEL_PATH}")except Exception as e: print(f"Model path resolution failed: {e}") MODEL_PATH = None
try: SCALER_PATH = resolve_artifact( LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME ) print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e: print(f"Scaler path resolution failed: {e}") SCALER_PATH = None
try: METADATA_PATH = resolve_artifact( LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME ) print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e: print(f"Metadata path resolution failed: {e}") METADATA_PATH = None
try: METADATA = load_metadata(METADATA_PATH) print(f"Metadata loaded: {len(METADATA)} entries")except Exception as e: print(f"Metadata loading failed: {e}") METADATA = {}
# Queuing configurationQUEUE_MAX_SIZE = 32# Apply a small per-event concurrency limit to avoid relying on the deprecated# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2
def try_load_model(path: Optional[Path], model_type: str, model_format: str): if not path: return None try: if model_type == "svm" or model_format == "joblib": model = joblib.load(path) else: model = load_model(path) print("Loaded model from", path) return model except Exception as exc: # pragma: no cover - runtime diagnostics print("Failed to load model", path, exc) return None
FEATURE_COLUMNS: List[str] = list(DEFAULT_FEATURE_COLUMNS)LABEL_CLASSES: List[str] = []LABEL_COLUMN: str = "Fault"SEQUENCE_LENGTH: int = DEFAULT_SEQUENCE_LENGTHDEFAULT_WINDOW_STRIDE: int = DEFAULT_STRIDEMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"
def _model_output_path(filename: str) -> str: return str(MODEL_OUTPUT_DIR / Path(filename).name)
MODEL_FILENAME_BY_TYPE: Dict[str, str] = { "cnn_lstm": Path(LOCAL_MODEL_FILE).name, "tcn": "pmu_tcn_model.keras", "svm": "pmu_svm_model.joblib",}
REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path( os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
TRAINING_DATA_REPO = os.environ.get( "PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)
GITHUB_CONTENT_CACHE: Dict[str, List[Dict[str, Any]]] = {}
APP_CSS = """#available-files-section { position: relative; display: flex; flex-direction: column; gap: 0.75rem; border-radius: 0.75rem; isolation: isolate;}
#available-files-grid { position: static; overflow: visible;}
#available-files-grid .form { position: static; min-height: 16rem;}
#available-files-grid .wrap { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.5rem; max-height: 24rem; min-height: 16rem; overflow-y: auto; padding-right: 0.25rem;}
#available-files-grid .wrap > div { min-width: 0;}
#available-files-grid .wrap label { margin: 0; display: flex; align-items: center; padding: 0.45rem 0.65rem; border-radius: 0.65rem; background-color: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease, border-color 0.2s ease; min-height: 2.5rem;}
#available-files-grid .wrap label:hover { background-color: rgba(90, 200, 250, 0.16); border-color: rgba(90, 200, 250, 0.4);}
#available-files-grid .wrap label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
#available-files-section .gradio-loading,#available-files-grid .gradio-loading { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.92); border-radius: 0.75rem; z-index: 999; padding: 1.5rem; pointer-events: auto;}
#available-files-grid .gradio-loading > * { width: 100%;}
#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,#available-files-grid .gradio-loading [role="progressbar"],#available-files-grid .gradio-loading .wrap,#available-files-grid .gradio-loading .inner { width: 100% !important; max-width: none !important;}
#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label { text-align: center;}
#date-browser-row { gap: 0.75rem;}
#date-browser-row .date-browser-column { flex: 1 1 0%; min-width: 0;}
#date-browser-row .date-browser-column > .gradio-dropdown,#date-browser-row .date-browser-column > .gradio-button { width: 100%;}
#date-browser-row .date-browser-column > .gradio-dropdown > div { width: 100%;}
#date-browser-row .date-browser-column .gradio-button { justify-content: center;}
#training-files-summary textarea { max-height: 12rem; overflow-y: auto;}
#download-selected-button { width: 100%; position: relative; z-index: 0;}
#download-selected-button .gradio-button { width: 100%; justify-content: center;}
#artifact-download-row { gap: 0.75rem;}
#artifact-download-row .artifact-download-button { flex: 1 1 0%; min-width: 0;}
#artifact-download-row .artifact-download-button .gradio-button { width: 100%; justify-content: center;}"""
def _github_cache_key(path: str) -> str: return path or "__root__"
def _github_api_url(path: str) -> str: clean_path = path.strip("/") base = f"https://api.github.com/repos/{TRAINING_DATA_REPO}/contents" if clean_path: return f"{base}/{clean_path}?ref={TRAINING_DATA_BRANCH}" return f"{base}?ref={TRAINING_DATA_BRANCH}"
def list_remote_directory( path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]: key = _github_cache_key(path) if not force_refresh and key in GITHUB_CONTENT_CACHE: return GITHUB_CONTENT_CACHE[key]
url = _github_api_url(path) response = requests.get(url, timeout=30) if response.status_code != 200: raise RuntimeError( f"GitHub API request failed for `{path or '.'}` (status {response.status_code})." )
payload = response.json() if not isinstance(payload, list): raise RuntimeError( "Unexpected GitHub API payload. Expected a directory listing." )
GITHUB_CONTENT_CACHE[key] = payload return payload
def list_remote_years(force_refresh: bool = False) -> List[str]: entries = list_remote_directory("", force_refresh=force_refresh) years = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(years)
def list_remote_months(year: str, *, force_refresh: bool = False) -> List[str]: if not year: return [] entries = list_remote_directory(year, force_refresh=force_refresh) months = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(months)
def list_remote_days( year: str, month: str, *, force_refresh: bool = False) -> List[str]: if not year or not month: return [] entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh) days = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(days)
def list_remote_files( year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]: if not year or not month or not day: return [] entries = list_remote_directory( f"{year}/{month}/{day}", force_refresh=force_refresh ) files = [item["name"] for item in entries if item.get("type") == "file"] return sorted(files)
def download_repository_file(year: str, month: str, day: str, filename: str) -> Path: if not filename: raise ValueError("Filename cannot be empty when downloading repository data.")
relative_parts = [part for part in (year, month, day, filename) if part] if len(relative_parts) < 4: raise ValueError("Provide year, month, day, and filename to download a CSV.")
relative_path = "/".join(relative_parts) raw_url = ( f"https://raw.githubusercontent.com/{TRAINING_DATA_REPO}/" f"{TRAINING_DATA_BRANCH}/{relative_path}" )
response = requests.get(raw_url, stream=True, timeout=120) if response.status_code != 200: raise RuntimeError( f"Failed to download `{relative_path}` (status {response.status_code})." )
target_dir = TRAINING_DATA_DIR.joinpath(year, month, day) target_dir.mkdir(parents=True, exist_ok=True) target_path = target_dir / filename
with open(target_path, "wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): if chunk: handle.write(chunk)
return target_path
def _normalise_header(name: str) -> str: return str(name).strip().lower()
def guess_label_from_columns( columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]: if not columns: return preferred
lookup = {_normalise_header(col): str(col) for col in columns}
if preferred: preferred_stripped = preferred.strip() for col in columns: if str(col).strip() == preferred_stripped: return str(col) preferred_norm = _normalise_header(preferred) if preferred_norm in lookup: return lookup[preferred_norm]
for guess in TRAINING_LABEL_GUESSES: guess_norm = _normalise_header(guess) if guess_norm in lookup: return lookup[guess_norm]
for col in columns: if _normalise_header(col).startswith("fault"): return str(col)
return str(columns[0])
def summarise_training_files(paths: Sequence[str], notes: Sequence[str]) -> str: lines = [Path(path).name for path in paths] lines.extend(notes) return "\n".join(lines) if lines else "No training files available."
def read_training_status(status_file_path: str) -> str: """Read the current training status from file.""" try: if Path(status_file_path).exists(): with open(status_file_path, "r") as f: return f.read().strip() except Exception: pass return "Training status unavailable"
def _persist_uploaded_file(file_obj) -> Optional[Path]: if file_obj is None: return None
if isinstance(file_obj, (str, Path)): source = Path(file_obj) original_name = source.name else: source = Path(getattr(file_obj, "name", "") or getattr(file_obj, "path", "")) original_name = getattr(file_obj, "orig_name", source.name) or source.name if not source or not source.exists(): return None
original_name = Path(original_name).name or source.name
base_path = Path(original_name) destination = TRAINING_UPLOAD_DIR / base_path.name counter = 1 while destination.exists(): suffix = base_path.suffix or ".csv" destination = TRAINING_UPLOAD_DIR / f"{base_path.stem}_{counter}{suffix}" counter += 1
shutil.copy2(source, destination) return destination
def prepare_training_paths( paths: Sequence[str], current_label: str, cleanup_missing: bool = False): valid_paths: List[str] = [] notes: List[str] = [] columns_map: Dict[str, str] = {} for path in paths: try: df = load_measurement_csv(path) except Exception as exc: # pragma: no cover - user file diagnostics notes.append(f"⚠️ Skipped {Path(path).name}: {exc}") if cleanup_missing: try: Path(path).unlink(missing_ok=True) except Exception: pass continue valid_paths.append(str(path)) for col in df.columns: columns_map[_normalise_header(col)] = str(col)
summary = summarise_training_files(valid_paths, notes) preferred = current_label or LABEL_COLUMN dropdown_choices = ( sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN] ) guessed = guess_label_from_columns(dropdown_choices, preferred) dropdown_value = guessed or preferred or LABEL_COLUMN
return ( valid_paths, summary, gr.update(choices=dropdown_choices, value=dropdown_value), )
def append_training_files(new_files, existing_paths: Sequence[str], current_label: str): if isinstance(existing_paths, (str, Path)): paths: List[str] = [str(existing_paths)] elif existing_paths is None: paths = [] else: paths = list(existing_paths) if new_files: for file in new_files: persisted = _persist_uploaded_file(file) if persisted is None: continue path_str = str(persisted) if path_str not in paths: paths.append(path_str)
return prepare_training_paths(paths, current_label, cleanup_missing=True)
def load_repository_training_files(current_label: str, force_refresh: bool = False): if force_refresh: # Clearing the cache is enough because downloads are now on-demand. for cached in list(TRAINING_DATA_DIR.glob("*")): # On refresh we keep previously downloaded files; no deletion required. # The flag triggers downstream UI updates only. break
csv_paths = sorted( str(path) for path in TRAINING_DATA_DIR.rglob("*.csv") if path.is_file() ) if not csv_paths: message = ( "No local database CSVs are available yet. Use the database browser " "below to download specific days before training." ) default_label = current_label or LABEL_COLUMN or "Fault" return ( [], message, gr.update(choices=[default_label], value=default_label), message, )
valid_paths, summary, label_update = prepare_training_paths( csv_paths, current_label, cleanup_missing=False )
info = ( f"Ready with {len(valid_paths)} CSV file(s) cached locally under " f"the database cache `{TRAINING_DATA_DIR}`." )
return valid_paths, summary, label_update, info
def refresh_remote_browser(force_refresh: bool = False): if force_refresh: GITHUB_CONTENT_CACHE.clear() try: years = list_remote_years(force_refresh=force_refresh) if years: message = "Select a year, month, and day to list available CSV files." else: message = ( "⚠️ No directories were found in the database root. Verify the upstream " "structure." ) return ( gr.update(choices=years, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to query database: {exc}", )
def on_year_change(year: Optional[str]): if not year: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a year to continue.", ) try: months = list_remote_months(year) message = ( f"Year `{year}` selected. Choose a month to drill down." if months else f"⚠️ No months available under `{year}`." ) return ( gr.update(choices=months, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list months: {exc}", )
def on_month_change(year: Optional[str], month: Optional[str]): if not year or not month: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a month to continue.", ) try: days = list_remote_days(year, month) message = ( f"Month `{year}/{month}` ready. Pick a day to view files." if days else f"⚠️ No day folders found under `{year}/{month}`." ) return ( gr.update(choices=days, value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list days: {exc}", )
def on_day_change(year: Optional[str], month: Optional[str], day: Optional[str]): if not year or not month or not day: return ( gr.update(choices=[], value=[]), "Select a day to load file names.", ) try: files = list_remote_files(year, month, day) message = ( f"{len(files)} file(s) available for `{year}/{month}/{day}`." if files else f"⚠️ No CSV files found under `{year}/{month}/{day}`." ) return ( gr.update(choices=files, value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=[]), f"⚠️ Failed to list files: {exc}", )
def download_selected_files( year: Optional[str], month: Optional[str], day: Optional[str], filenames: Sequence[str], current_label: str,): if not filenames: message = "Select at least one CSV before downloading." local = load_repository_training_files(current_label) return (*local, gr.update(), message)
success: List[str] = [] notes: List[str] = [] for filename in filenames: try: path = download_repository_file( year or "", month or "", day or "", filename ) success.append(str(path)) except Exception as exc: notes.append(f"⚠️ {filename}: {exc}")
local = load_repository_training_files(current_label)
message_lines = [] if success: message_lines.append( f"Downloaded {len(success)} file(s) to the database cache `{TRAINING_DATA_DIR}`." ) if notes: message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_day_bundle( year: Optional[str], month: Optional[str], day: Optional[str], current_label: str,): if not (year and month and day): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year, month, and day before downloading an entire day.", )
try: files = list_remote_files(year, month, day) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to list CSVs for `{year}/{month}/{day}`: {exc}", )
if not files: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No CSV files were found for `{year}/{month}/{day}`.", )
result = list(download_selected_files(year, month, day, files, current_label)) result[-1] = ( f"Downloaded all {len(files)} CSV file(s) for `{year}/{month}/{day}`.\n" f"{result[-1]}" ) return tuple(result)
def download_month_bundle( year: Optional[str], month: Optional[str], current_label: str): if not (year and month): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year and month before downloading an entire month.", )
try: days = list_remote_days(year, month) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate days for `{year}/{month}`: {exc}", )
if not days: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No day folders were found for `{year}/{month}`.", )
downloaded = 0 notes: List[str] = [] for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}/{month}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_year_bundle(year: Optional[str], current_label: str): if not year: local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year before downloading an entire year of CSVs.", )
try: months = list_remote_months(year) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate months for `{year}`: {exc}", )
if not months: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No month folders were found for `{year}`.", )
downloaded = 0 notes: List[str] = [] for month in months: try: days = list_remote_days(year, month) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}`: {exc}") continue if not days: notes.append(f"⚠️ No day folders in `{year}/{month}`.") continue for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def clear_downloaded_cache(current_label: str): status_message = "" try: if TRAINING_DATA_DIR.exists(): shutil.rmtree(TRAINING_DATA_DIR) TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True) status_message = ( f"Cleared all downloaded CSVs from database cache `{TRAINING_DATA_DIR}`." ) except Exception as exc: status_message = f"⚠️ Failed to clear database cache: {exc}"
local = load_repository_training_files(current_label, force_refresh=True) remote = list(refresh_remote_browser(force_refresh=False)) if status_message: previous = remote[-1] if isinstance(previous, str) and previous: remote[-1] = f"{status_message}\n{previous}" else: remote[-1] = status_message
return (*local, *remote)
def normalise_output_directory(directory: Optional[str]) -> Path: base = Path(directory or MODEL_OUTPUT_DIR) base = base.expanduser() if not base.is_absolute(): base = (Path.cwd() / base).resolve() return base
def resolve_output_path( directory: Optional[Union[Path, str]], filename: Optional[str], fallback: str) -> Path: if isinstance(directory, Path): base = directory else: base = normalise_output_directory(directory) candidate = Path(filename or "").expanduser() if str(candidate): if candidate.is_absolute(): return candidate return (base / candidate).resolve() return (base / fallback).resolve()
ARTIFACT_FILE_EXTENSIONS: Tuple[str, ...] = ( ".keras", ".h5", ".joblib", ".pkl", ".json", ".onnx", ".zip", ".txt",)
def gather_directory_choices(current: Optional[str]) -> Tuple[List[str], str]: base = normalise_output_directory(current or str(MODEL_OUTPUT_DIR)) candidates = {str(base)} try: for candidate in base.parent.iterdir(): if candidate.is_dir(): candidates.add(str(candidate.resolve())) except Exception: pass return sorted(candidates), str(base)
def gather_artifact_choices( directory: Optional[str], selection: Optional[str] = None) -> Tuple[List[Tuple[str, str]], Optional[str]]: base = normalise_output_directory(directory) choices: List[Tuple[str, str]] = [] selected_value: Optional[str] = None if base.exists(): try: artifacts = sorted( [ path for path in base.iterdir() if path.is_file() and ( not ARTIFACT_FILE_EXTENSIONS or path.suffix.lower() in ARTIFACT_FILE_EXTENSIONS ) ], key=lambda path: path.name.lower(), ) choices = [(artifact.name, str(artifact)) for artifact in artifacts] except Exception: choices = []
if selection and any(value == selection for _, value in choices): selected_value = selection elif choices: selected_value = choices[0][1]
return choices, selected_value
def download_button_state(path: Optional[Union[str, Path]]): if not path: return gr.update(value=None, visible=False) candidate = Path(path) if candidate.exists(): return gr.update(value=str(candidate), visible=True) return gr.update(value=None, visible=False)
def clear_training_files(): default_label = LABEL_COLUMN or "Fault" for cached_file in TRAINING_UPLOAD_DIR.glob("*"): try: if cached_file.is_file(): cached_file.unlink(missing_ok=True) except Exception: pass return ( [], "No training files selected.", gr.update(choices=[default_label], value=default_label), gr.update(value=None), )
PROJECT_OVERVIEW_MD = """## Project Overview
This project focuses on classifying faults in electrical transmission lines andgrid-connected photovoltaic (PV) systems by combining ensemble learningtechniques with deep neural architectures.
## Datasets
### Transmission Line Fault Dataset- 134,406 samples collected from Phasor Measurement Units (PMUs)- 14 monitored channels covering currents, voltages, magnitudes, frequency, and phase angles- Labels span symmetrical and asymmetrical faults: NF, L-G, LL, LL-G, LLL, and LLL-G- Time span: 0 to 5.7 seconds with high-frequency sampling
### Grid-Connected PV System Fault Dataset- 2,163,480 samples from 16 experimental scenarios- 14 features including PV array measurements (Ipv, Vpv, Vdc), three-phase currents/voltages, aggregate magnitudes (Iabc, Vabc), and frequency indicators (If, Vf)- Captures array, inverter, grid anomaly, feedback sensor, and MPPT controller faults at 9.9989 μs sampling intervals
## Data Format Quick Reference
Each measurement file may be comma or tab separated and typically exposes thefollowing ordered columns:
1. `Timestamp`2. `[325] UPMU_SUB22:FREQ` – system frequency (Hz)3. `[326] UPMU_SUB22:DFDT` – frequency rate-of-change4. `[327] UPMU_SUB22:FLAG` – PMU status flag5. `[328] UPMU_SUB22-L1:MAG` – phase A voltage magnitude6. `[329] UPMU_SUB22-L1:ANG` – phase A voltage angle7. `[330] UPMU_SUB22-L2:MAG` – phase B voltage magnitude8. `[331] UPMU_SUB22-L2:ANG` – phase B voltage angle9. `[332] UPMU_SUB22-L3:MAG` – phase C voltage magnitude10. `[333] UPMU_SUB22-L3:ANG` – phase C voltage angle11. `[334] UPMU_SUB22-C1:MAG` – phase A current magnitude12. `[335] UPMU_SUB22-C1:ANG` – phase A current angle13. `[336] UPMU_SUB22-C2:MAG` – phase B current magnitude14. `[337] UPMU_SUB22-C2:ANG` – phase B current angle15. `[338] UPMU_SUB22-C3:MAG` – phase C current magnitude16. `[339] UPMU_SUB22-C3:ANG` – phase C current angle
The training tab automatically downloads the latest CSV exports from the`VincentCroft/ThesisModelData` repository and concatenates them before buildingsliding windows.
## Models Developed
1. **Support Vector Machine (SVM)** – provides the classical machine learning baseline with balanced accuracy across both datasets (85% PMU / 83% PV).2. **CNN-LSTM** – couples convolutional feature extraction with temporal memory, achieving 92% PMU / 89% PV accuracy.3. **Temporal Convolutional Network (TCN)** – leverages dilated convolutions for long-range context and delivers the best trade-off between accuracy and training time (94% PMU / 91% PV).
## Results Summary
- **Transmission Line Fault Classification**: SVM 85%, CNN-LSTM 92%, TCN 94%- **PV System Fault Classification**: SVM 83%, CNN-LSTM 89%, TCN 91%
Use the **Inference** tab to score new PMU/PV windows and the **Training** tab tofine-tune or retrain any of the supported models directly within Hugging FaceSpaces. The logs panel will surface TensorBoard archives whenever deep-learningmodels are trained."""
def load_measurement_csv(path: str) -> pd.DataFrame: """Read a PMU/PV measurement file with flexible separators and column mapping."""
try: df = pd.read_csv(path, sep=None, engine="python", encoding="utf-8-sig") except Exception: df = None for separator in ("\t", ",", ";"): try: df = pd.read_csv( path, sep=separator, engine="python", encoding="utf-8-sig" ) break except Exception: df = None if df is None: raise
# Clean column names df.columns = [str(col).strip() for col in df.columns]
print(f"Loaded CSV with {len(df)} rows and {len(df.columns)} columns") print(f"Columns: {list(df.columns)}") print(f"Data shape: {df.shape}")
# Check if we have enough data for training if len(df) < 100: print( f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training." )
# Check for label column has_label = any( col.lower() in ["fault", "label", "class", "target"] for col in df.columns ) if not has_label: print( "Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples." ) df["Fault"] = "Normal" # Add dummy label for training
# Create column mapping - map similar column names to expected format column_mapping = {} expected_cols = list(REQUIRED_PMU_COLUMNS)
# If we have at least the right number of numeric columns after Timestamp, use positional mapping if "Timestamp" in df.columns: numeric_cols = [col for col in df.columns if col != "Timestamp"] if len(numeric_cols) >= len(expected_cols): # Map by position (after Timestamp) for i, expected_col in enumerate(expected_cols): if i < len(numeric_cols): column_mapping[numeric_cols[i]] = expected_col
# Rename columns to match expected format df = df.rename(columns=column_mapping)
# Check if we have the required columns after mapping missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns] if missing: # If still missing, try a more flexible approach available_numeric = df.select_dtypes(include=[np.number]).columns.tolist() if len(available_numeric) >= len(expected_cols): # Use the first N numeric columns for i, expected_col in enumerate(expected_cols): if i < len(available_numeric): if available_numeric[i] not in df.columns: continue df = df.rename(columns={available_numeric[i]: expected_col})
# Recheck missing columns missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns]
if missing: missing_str = ", ".join(missing) available_str = ", ".join(df.columns.tolist()) raise ValueError( f"Missing required PMU feature columns: {missing_str}. " f"Available columns: {available_str}. " "Please ensure your CSV has the correct format with Timestamp followed by PMU measurements." )
return df
def apply_metadata(metadata: Dict[str, Any]) -> None: global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMAT FEATURE_COLUMNS = [ str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS) ] LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])] LABEL_COLUMN = str(metadata.get("label_column", "Fault")) SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH)) DEFAULT_WINDOW_STRIDE = int(metadata.get("stride", DEFAULT_STRIDE)) MODEL_TYPE = str(metadata.get("model_type", "cnn_lstm")).lower() MODEL_FORMAT = str( metadata.get("model_format", "joblib" if MODEL_TYPE == "svm" else "keras") ).lower()
apply_metadata(METADATA)
def sync_label_classes_from_model(model: Optional[object]) -> None: global LABEL_CLASSES if model is None: return if hasattr(model, "classes_"): LABEL_CLASSES = [str(label) for label in getattr(model, "classes_")] elif not LABEL_CLASSES and hasattr(model, "output_shape"): LABEL_CLASSES = [str(i) for i in range(int(model.output_shape[-1]))]
# Load model and scaler with error handlingprint("Loading model and scaler...")try: MODEL = try_load_model(MODEL_PATH, MODEL_TYPE, MODEL_FORMAT) print(f"Model loaded: {MODEL is not None}")except Exception as e: print(f"Model loading failed: {e}") MODEL = None
try: SCALER = try_load_scaler(SCALER_PATH) print(f"Scaler loaded: {SCALER is not None}")except Exception as e: print(f"Scaler loading failed: {e}") SCALER = None
try: sync_label_classes_from_model(MODEL) print("Label classes synchronized")except Exception as e: print(f"Label sync failed: {e}")
print("Application initialization completed.")print( f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")
def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None: global MODEL_PATH, SCALER_PATH, METADATA_PATH, MODEL, SCALER, METADATA MODEL_PATH = model_path SCALER_PATH = scaler_path METADATA_PATH = metadata_path METADATA = load_metadata(metadata_path) apply_metadata(METADATA) MODEL = try_load_model(model_path, MODEL_TYPE, MODEL_FORMAT) SCALER = try_load_scaler(scaler_path) sync_label_classes_from_model(MODEL)
# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------
def ensure_ready(): if MODEL is None or SCALER is None: raise RuntimeError( "The model and feature scaler are not available. Upload the trained model " "(for example `pmu_cnn_lstm_model.keras`, `pmu_tcn_model.keras`, or `pmu_svm_model.joblib`), " "the feature scaler (`pmu_feature_scaler.pkl`), and the metadata JSON (`pmu_metadata.json`) to the Space root " "or configure the Hugging Face Hub environment variables so the artifacts can be downloaded " "automatically." )
def parse_text_features(text: str) -> np.ndarray: cleaned = re.sub(r"[;\n\t]+", ",", text.strip()) arr = np.fromstring(cleaned, sep=",") if arr.size == 0: raise ValueError( "No feature values were parsed. Please enter comma-separated numbers." ) return arr.astype(np.float32)
def apply_scaler(sequences: np.ndarray) -> np.ndarray: if SCALER is None: return sequences shape = sequences.shape flattened = sequences.reshape(-1, shape[-1]) scaled = SCALER.transform(flattened) return scaled.reshape(shape)
def make_sliding_windows( data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray: if data.shape[0] < sequence_length: raise ValueError( f"The dataset contains {data.shape[0]} rows which is less than the requested sequence " f"length {sequence_length}. Provide more samples or reduce the sequence length." ) windows = [ data[start : start + sequence_length] for start in range(0, data.shape[0] - sequence_length + 1, stride) ] return np.stack(windows)
def dataframe_to_sequences( df: pd.DataFrame, *, sequence_length: int, stride: int, feature_columns: Sequence[str], drop_label: bool = True,) -> np.ndarray: work_df = df.copy() if drop_label and LABEL_COLUMN in work_df.columns: work_df = work_df.drop(columns=[LABEL_COLUMN]) if "Timestamp" in work_df.columns: work_df = work_df.sort_values("Timestamp")
available_cols = [c for c in feature_columns if c in work_df.columns] n_features = len(feature_columns) if available_cols and len(available_cols) == n_features: array = work_df[available_cols].astype(np.float32).to_numpy() return make_sliding_windows(array, sequence_length, stride)
numeric_df = work_df.select_dtypes(include=[np.number]) array = numeric_df.astype(np.float32).to_numpy() if array.shape[1] == n_features * sequence_length: return array.reshape(array.shape[0], sequence_length, n_features) if sequence_length == 1 and array.shape[1] == n_features: return array.reshape(array.shape[0], 1, n_features) raise ValueError( "CSV columns do not match the expected feature layout. Include the full PMU feature set " "or provide pre-shaped sliding window data." )
def label_name(index: int) -> str: if 0 <= index < len(LABEL_CLASSES): return str(LABEL_CLASSES[index]) return f"class_{index}"
def format_predictions(probabilities: np.ndarray) -> pd.DataFrame: rows: List[Dict[str, object]] = [] order = np.argsort(probabilities, axis=1)[:, ::-1] for idx, (prob_row, ranking) in enumerate(zip(probabilities, order)): top_idx = int(ranking[0]) top_label = label_name(top_idx) top_conf = float(prob_row[top_idx]) top3 = [f"{label_name(i)} ({prob_row[i]*100:.2f}%)" for i in ranking[:3]] rows.append( { "window": idx, "predicted_label": top_label, "confidence": round(top_conf, 4), "top3": " | ".join(top3), } ) return pd.DataFrame(rows)
def probabilities_to_json(probabilities: np.ndarray) -> List[Dict[str, object]]: payload: List[Dict[str, object]] = [] for idx, prob_row in enumerate(probabilities): payload.append( { "window": int(idx), "probabilities": { label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0]) }, } ) return payload
def predict_sequences( sequences: np.ndarray,) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: ensure_ready() sequences = apply_scaler(sequences.astype(np.float32)) if MODEL_TYPE == "svm": flattened = sequences.reshape(sequences.shape[0], -1) if hasattr(MODEL, "predict_proba"): probs = MODEL.predict_proba(flattened) else: raise RuntimeError( "Loaded SVM model does not expose predict_proba. Retrain with probability=True." ) else: probs = MODEL.predict(sequences, verbose=0) table = format_predictions(probs) json_probs = probabilities_to_json(probs) architecture = MODEL_TYPE.replace("_", "-").upper() status = f"Generated {len(sequences)} windows. {architecture} model output dimension: {probs.shape[1]}." return status, table, json_probs
def predict_from_text( text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: arr = parse_text_features(text) n_features = len(FEATURE_COLUMNS) if arr.size % n_features != 0: raise ValueError( f"The number of values ({arr.size}) is not a multiple of the feature dimension " f"({n_features}). Provide values in groups of {n_features}." ) timesteps = arr.size // n_features if timesteps != sequence_length: raise ValueError( f"Detected {timesteps} timesteps which does not match the configured sequence length " f"({sequence_length})." ) sequences = arr.reshape(1, sequence_length, n_features) status, table, probs = predict_sequences(sequences) status = f"Single window prediction complete. {status}" return status, table, probs
def predict_from_csv( file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: df = load_measurement_csv(file_obj.name) sequences = dataframe_to_sequences( df, sequence_length=sequence_length, stride=stride, feature_columns=FEATURE_COLUMNS, ) status, table, probs = predict_sequences(sequences) status = f"CSV processed successfully. Generated {len(sequences)} windows. {status}" return status, table, probs
# --------------------------------------------------------------------------------------# Training helpers# --------------------------------------------------------------------------------------
def classification_report_to_dataframe(report: Dict[str, Any]) -> pd.DataFrame: rows: List[Dict[str, Any]] = [] for label, metrics in report.items(): if isinstance(metrics, dict): row = {"label": label} for key, value in metrics.items(): if key == "support": row[key] = int(value) else: row[key] = round(float(value), 4) rows.append(row) else: rows.append({"label": label, "accuracy": round(float(metrics), 4)}) return pd.DataFrame(rows)
def confusion_matrix_to_dataframe( confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame: if not confusion: return pd.DataFrame() df = pd.DataFrame(confusion, index=list(labels), columns=list(labels)) df.index.name = "True Label" df.columns.name = "Predicted Label" return df
# --------------------------------------------------------------------------------------# Gradio interface# --------------------------------------------------------------------------------------
def build_interface() -> gr.Blocks: theme = gr.themes.Soft( primary_hue="sky", secondary_hue="blue", neutral_hue="gray" ).set( body_background_fill="#1f1f1f", body_text_color="#f5f5f5", block_background_fill="#262626", block_border_color="#333333", button_primary_background_fill="#5ac8fa", button_primary_background_fill_hover="#48b5eb", button_primary_border_color="#38bdf8", button_primary_text_color="#0f172a", button_secondary_background_fill="#3f3f46", button_secondary_text_color="#f5f5f5", )
def _normalise_directory_string(value: Optional[Union[str, Path]]) -> str: if value is None: return "" path = Path(value).expanduser() try: return str(path.resolve()) except Exception: return str(path)
with gr.Blocks( title="Fault Classification - PMU Data", theme=theme, css=APP_CSS ) as demo: gr.Markdown("# Fault Classification for PMU & PV Data") gr.Markdown( "🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers." ) if MODEL is None or SCALER is None: gr.Markdown( "⚠️ **Artifacts Missing** — Upload `pmu_cnn_lstm_model.keras`, " "`pmu_feature_scaler.pkl`, and `pmu_metadata.json` to enable inference, " "or configure the Hugging Face Hub environment variables so they can be downloaded." ) else: class_count = len(LABEL_CLASSES) if LABEL_CLASSES else "unknown" gr.Markdown( f"Loaded a **{MODEL_TYPE.upper()}** model ({MODEL_FORMAT.upper()}) with " f"{len(FEATURE_COLUMNS)} features, sequence length **{SEQUENCE_LENGTH}**, and " f"{class_count} target classes. Use the tabs below to run inference or fine-tune " "the model with your own CSV files." )
with gr.Accordion("Feature Reference", open=False): gr.Markdown( f"Each time window expects **{len(FEATURE_COLUMNS)} features** ordered as follows:\n" + "\n".join(f"- {name}" for name in FEATURE_COLUMNS) ) gr.Markdown( f"Default training parameters: **sequence length = {SEQUENCE_LENGTH}**, " f"**stride = {DEFAULT_WINDOW_STRIDE}**. Adjust them in the tabs as needed." )
with gr.Tabs(): with gr.Tab("Overview"): gr.Markdown(PROJECT_OVERVIEW_MD) with gr.Tab("Inference"): gr.Markdown("## Run Inference") with gr.Row(): file_in = gr.File(label="Upload PMU CSV", file_types=[".csv"]) text_in = gr.Textbox( lines=4, label="Or paste a single window (comma separated)", placeholder="49.97772,1.215825E-38,...", )
with gr.Row(): sequence_length_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length (timesteps)", ) stride_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="CSV window stride", )
predict_btn = gr.Button("🚀 Run Inference", variant="primary") status_out = gr.Textbox(label="Status", interactive=False) table_out = gr.Dataframe( headers=["window", "predicted_label", "confidence", "top3"], label="Predictions", interactive=False, ) probs_out = gr.JSON(label="Per-window probabilities")
def _run_prediction(file_obj, text, sequence_length, stride): sequence_length = int(sequence_length) stride = int(stride) try: if file_obj is not None: return predict_from_csv(file_obj, sequence_length, stride) if text and text.strip(): return predict_from_text(text, sequence_length) return ( "Please upload a CSV file or provide feature values.", pd.DataFrame(), [], ) except Exception as exc: return f"Prediction failed: {exc}", pd.DataFrame(), []
predict_btn.click( _run_prediction, inputs=[file_in, text_in, sequence_length_input, stride_input], outputs=[status_out, table_out, probs_out], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Tab("Training"): gr.Markdown("## Train or Fine-tune the Model") gr.Markdown( "Training data is automatically downloaded from the database. " "Refresh the cache if new files are added upstream." )
training_files_state = gr.State([]) with gr.Row(): with gr.Column(scale=3): training_files_summary = gr.Textbox( label="Database training CSVs", value="Training dataset not loaded yet.", lines=4, interactive=False, elem_id="training-files-summary", ) with gr.Column(scale=2, min_width=240): dataset_info = gr.Markdown( "No local database CSVs downloaded yet.", ) dataset_refresh = gr.Button( "🔄 Reload dataset from database", variant="secondary", ) clear_cache_button = gr.Button( "🧹 Clear downloaded cache", variant="secondary", )
with gr.Accordion("📂 DataBaseBrowser", open=False): gr.Markdown( "Browse the upstream database by date and download only the CSVs you need." ) with gr.Row(elem_id="date-browser-row"): with gr.Column(scale=1, elem_classes=["date-browser-column"]): year_selector = gr.Dropdown(label="Year", choices=[]) year_download_button = gr.Button( "⬇️ Download year CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): month_selector = gr.Dropdown(label="Month", choices=[]) month_download_button = gr.Button( "⬇️ Download month CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): day_selector = gr.Dropdown(label="Day", choices=[]) day_download_button = gr.Button( "⬇️ Download day CSVs", variant="secondary" ) with gr.Column(elem_id="available-files-section"): available_files = gr.CheckboxGroup( label="Available CSV files", choices=[], value=[], elem_id="available-files-grid", ) download_button = gr.Button( "⬇️ Download selected CSVs", variant="secondary", elem_id="download-selected-button", ) repo_status = gr.Markdown( "Click 'Reload dataset from database' to fetch the directory tree." )
with gr.Row(): label_input = gr.Dropdown( value=LABEL_COLUMN, choices=[LABEL_COLUMN], allow_custom_value=True, label="Label column name", ) model_selector = gr.Radio( choices=["CNN-LSTM", "TCN", "SVM"], value=( "TCN" if MODEL_TYPE == "tcn" else ("SVM" if MODEL_TYPE == "svm" else "CNN-LSTM") ), label="Model architecture", ) sequence_length_train = gr.Slider( minimum=4, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length", ) stride_train = gr.Slider( minimum=1, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="Stride", )
model_default = MODEL_FILENAME_BY_TYPE.get( MODEL_TYPE, Path(LOCAL_MODEL_FILE).name )
with gr.Row(): validation_train = gr.Slider( minimum=0.05, maximum=0.4, step=0.05, value=0.2, label="Validation split", ) batch_train = gr.Slider( minimum=32, maximum=512, step=32, value=128, label="Batch size", ) epochs_train = gr.Slider( minimum=5, maximum=100, step=5, value=50, label="Epochs", )
directory_choices, directory_default = gather_directory_choices( str(MODEL_OUTPUT_DIR) ) artifact_choices, default_artifact = gather_artifact_choices( directory_default )
with gr.Row(): output_directory = gr.Dropdown( value=directory_default, label="Output directory", choices=directory_choices, allow_custom_value=True, ) model_name = gr.Textbox( value=model_default, label="Model output filename", ) scaler_name = gr.Textbox( value=Path(LOCAL_SCALER_FILE).name, label="Scaler output filename", ) metadata_name = gr.Textbox( value=Path(LOCAL_METADATA_FILE).name, label="Metadata output filename", )
with gr.Row(): artifact_browser = gr.Dropdown( label="Saved artifacts in directory", choices=artifact_choices, value=default_artifact, ) artifact_download_button = gr.DownloadButton( "⬇️ Download selected artifact", value=default_artifact, visible=bool(default_artifact), variant="secondary", )
def on_output_directory_change(selected_dir, current_selection): choices, normalised = gather_directory_choices(selected_dir) artifact_options, selected = gather_artifact_choices( normalised, current_selection ) return ( gr.update(choices=choices, value=normalised), gr.update(choices=artifact_options, value=selected), download_button_state(selected), )
def on_artifact_change(selected_path): return download_button_state(selected_path)
output_directory.change( on_output_directory_change, inputs=[output_directory, artifact_browser], outputs=[ output_directory, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
artifact_browser.change( on_artifact_change, inputs=[artifact_browser], outputs=[artifact_download_button], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Row(elem_id="artifact-download-row"): model_download_button = gr.DownloadButton( "⬇️ Download model file", value=None, visible=False, elem_classes=["artifact-download-button"], ) scaler_download_button = gr.DownloadButton( "⬇️ Download scaler file", value=None, visible=False, elem_classes=["artifact-download-button"], ) metadata_download_button = gr.DownloadButton( "⬇️ Download metadata file", value=None, visible=False, elem_classes=["artifact-download-button"], ) tensorboard_download_button = gr.DownloadButton( "⬇️ Download TensorBoard logs", value=None, visible=False, elem_classes=["artifact-download-button"], )
model_download_button.file_name = Path(LOCAL_MODEL_FILE).name scaler_download_button.file_name = Path(LOCAL_SCALER_FILE).name metadata_download_button.file_name = Path(LOCAL_METADATA_FILE).name tensorboard_download_button.file_name = "tensorboard_logs.zip"
tensorboard_toggle = gr.Checkbox( value=True, label="Enable TensorBoard logging (creates downloadable archive)", )
def _suggest_model_filename(choice: str, current_value: str): choice_key = (choice or "cnn_lstm").lower().replace("-", "_") suggested = MODEL_FILENAME_BY_TYPE.get( choice_key, Path(LOCAL_MODEL_FILE).name ) known_defaults = set(MODEL_FILENAME_BY_TYPE.values()) current_name = Path(current_value).name if current_value else "" if current_name and current_name not in known_defaults: return gr.update() return gr.update(value=suggested)
model_selector.change( _suggest_model_filename, inputs=[model_selector, model_name], outputs=model_name, )
with gr.Row(): train_button = gr.Button("🛠️ Start Training", variant="primary") progress_button = gr.Button( "📊 Check Progress", variant="secondary" )
# Training status display training_status = gr.Textbox(label="Training Status", interactive=False) report_output = gr.Dataframe( label="Classification report", interactive=False ) history_output = gr.JSON(label="Training history") confusion_output = gr.Dataframe( label="Confusion matrix", interactive=False )
# Message area at the bottom for progress updates with gr.Accordion("📋 Progress Messages", open=True): progress_messages = gr.Textbox( label="Training Messages", lines=8, max_lines=20, interactive=False, autoscroll=True, placeholder="Click 'Check Progress' to see training updates...", ) with gr.Row(): gr.Button("🗑️ Clear Messages", variant="secondary").click( lambda: "", outputs=[progress_messages] )
def _run_training( file_paths, label_column, model_choice, sequence_length, stride, validation_split, batch_size, epochs, output_dir, model_filename, scaler_filename, metadata_filename, enable_tensorboard, ): base_dir = normalise_output_directory(output_dir) try: base_dir.mkdir(parents=True, exist_ok=True)
model_path = resolve_output_path( base_dir, model_filename, Path(LOCAL_MODEL_FILE).name, ) scaler_path = resolve_output_path( base_dir, scaler_filename, Path(LOCAL_SCALER_FILE).name, ) metadata_path = resolve_output_path( base_dir, metadata_filename, Path(LOCAL_METADATA_FILE).name, )
model_path.parent.mkdir(parents=True, exist_ok=True) scaler_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True)
# Create status file path for progress tracking status_file = model_path.parent / "training_status.txt"
# Initialize status with open(status_file, "w") as f: f.write("Starting training setup...")
if not file_paths: raise ValueError( "No training CSVs were found in the database cache. " "Use 'Reload dataset from database' and try again." )
with open(status_file, "w") as f: f.write("Loading and validating CSV files...")
available_paths = [ path for path in file_paths if Path(path).exists() ] missing_paths = [ Path(path).name for path in file_paths if not Path(path).exists() ] if not available_paths: raise ValueError( "Database training dataset is unavailable. Reload the dataset and retry." )
dfs = [load_measurement_csv(path) for path in available_paths] combined = pd.concat(dfs, ignore_index=True)
# Validate data size and provide recommendations total_samples = len(combined) if total_samples < 100: print( f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results." ) print( "Automatically switching to SVM for small dataset compatibility." ) if model_choice in ["cnn_lstm", "tcn"]: model_choice = "svm" print( f"Model type changed to SVM for better small dataset performance." ) if total_samples < 10: raise ValueError( f"Insufficient data: {total_samples} samples. Need at least 10 samples for training." )
label_column = (label_column or LABEL_COLUMN).strip() if not label_column: raise ValueError("Label column name cannot be empty.")
model_choice = ( (model_choice or "CNN-LSTM").lower().replace("-", "_") ) if model_choice not in {"cnn_lstm", "tcn", "svm"}: raise ValueError( "Select CNN-LSTM, TCN, or SVM for the model architecture." )
with open(status_file, "w") as f: f.write( f"Starting {model_choice.upper()} training with {len(combined)} samples..." )
# Start training result = train_from_dataframe( combined, label_column=label_column, feature_columns=None, sequence_length=int(sequence_length), stride=int(stride), validation_split=float(validation_split), batch_size=int(batch_size), epochs=int(epochs), model_type=model_choice, model_path=model_path, scaler_path=scaler_path, metadata_path=metadata_path, enable_tensorboard=bool(enable_tensorboard), )
refresh_artifacts( Path(result["model_path"]), Path(result["scaler_path"]), Path(result["metadata_path"]), )
report_df = classification_report_to_dataframe( result["classification_report"] ) confusion_df = confusion_matrix_to_dataframe( result["confusion_matrix"], result["class_names"] ) tensorboard_dir = result.get("tensorboard_log_dir") tensorboard_zip = result.get("tensorboard_zip_path")
architecture = result["model_type"].replace("_", "-").upper() status = ( f"Training complete using a {architecture} architecture. " f"{result['num_sequences']} windows derived from " f"{result['num_samples']} rows across {len(available_paths)} file(s)." f" Artifacts saved to:" f"\n• Model: {result['model_path']}\n" f"• Scaler: {result['scaler_path']}\n" f"• Metadata: {result['metadata_path']}" )
status += f"\nLabel column used: {result.get('label_column', label_column)}"
if tensorboard_dir: status += ( f"\nTensorBoard logs directory: {tensorboard_dir}" f'\nRun `tensorboard --logdir "{tensorboard_dir}"` to inspect the training curves.' "\nDownload the archive below to explore the run offline." )
if missing_paths: skipped = ", ".join(missing_paths) status = f"⚠️ Skipped missing files: {skipped}\n" + status
artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir), result["model_path"] )
return ( status, report_df, result["history"], confusion_df, download_button_state(result["model_path"]), download_button_state(result["scaler_path"]), download_button_state(result["metadata_path"]), download_button_state(tensorboard_zip), gr.update(value=result.get("label_column", label_column)), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), ) except Exception as exc: artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir) ) return ( f"Training failed: {exc}", pd.DataFrame(), {}, pd.DataFrame(), download_button_state(None), download_button_state(None), download_button_state(None), download_button_state(None), gr.update(), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), )
def _check_progress(output_dir, model_filename, current_messages): """Check training progress by reading status file and accumulate messages.""" model_path = resolve_output_path( output_dir, model_filename, Path(LOCAL_MODEL_FILE).name ) status_file = model_path.parent / "training_status.txt" status_message = read_training_status(str(status_file))
# Add timestamp to the message from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S") new_message = f"[{timestamp}] {status_message}"
# Accumulate messages, keeping last 50 lines to prevent overflow if current_messages: lines = current_messages.split("\n") lines.append(new_message) # Keep only last 50 lines if len(lines) > 50: lines = lines[-50:] accumulated_messages = "\n".join(lines) else: accumulated_messages = new_message
return accumulated_messages
train_button.click( _run_training, inputs=[ training_files_state, label_input, model_selector, sequence_length_train, stride_train, validation_train, batch_train, epochs_train, output_directory, model_name, scaler_name, metadata_name, tensorboard_toggle, ], outputs=[ training_status, report_output, history_output, confusion_output, model_download_button, scaler_download_button, metadata_download_button, tensorboard_download_button, label_input, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
progress_button.click( _check_progress, inputs=[output_directory, model_name, progress_messages], outputs=[progress_messages], )
year_selector.change( on_year_change, inputs=[year_selector], outputs=[ month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_selector.change( on_month_change, inputs=[year_selector, month_selector], outputs=[day_selector, available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_selector.change( on_day_change, inputs=[year_selector, month_selector, day_selector], outputs=[available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
download_button.click( download_selected_files, inputs=[ year_selector, month_selector, day_selector, available_files, label_input, ], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
year_download_button.click( download_year_bundle, inputs=[year_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_download_button.click( download_month_bundle, inputs=[year_selector, month_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_download_button.click( download_day_bundle, inputs=[year_selector, month_selector, day_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _reload_dataset(current_label): local = load_repository_training_files( current_label, force_refresh=True ) remote = refresh_remote_browser(force_refresh=True) return (*local, *remote)
dataset_refresh.click( _reload_dataset, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
clear_cache_button.click( clear_downloaded_cache, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _initialise_dataset(): local = load_repository_training_files( LABEL_COLUMN, force_refresh=False ) remote = refresh_remote_browser(force_refresh=False) return (*local, *remote)
demo.load( _initialise_dataset, inputs=None, outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], queue=False, )
return demo
# --------------------------------------------------------------------------------------# Launch helpers# --------------------------------------------------------------------------------------
def resolve_server_port() -> int: for env_var in ("PORT", "GRADIO_SERVER_PORT"): value = os.environ.get(env_var) if value: try: return int(value) except ValueError: print(f"Ignoring invalid port value from {env_var}: {value}") return 7860
def main(): print("Building Gradio interface...") try: demo = build_interface() print("Interface built successfully") except Exception as e: print(f"Failed to build interface: {e}") import traceback
traceback.print_exc() return
print("Setting up queue...") try: demo.queue(max_size=QUEUE_MAX_SIZE) print("Queue configured") except Exception as e: print(f"Failed to configure queue: {e}")
try: port = resolve_server_port() print(f"Launching Gradio app on port {port}") demo.launch(server_name="0.0.0.0", server_port=port, show_error=True) except OSError as exc: print("Failed to launch on requested port:", exc) try: demo.launch(server_name="0.0.0.0", show_error=True) except Exception as e: print(f"Failed to launch completely: {e}") except Exception as e: print(f"Unexpected launch error: {e}") import traceback
traceback.print_exc()
if __name__ == "__main__": print("=" * 50) print("PMU Fault Classification App Starting") print(f"Python version: {os.sys.version}") print(f"Working directory: {os.getcwd()}") print(f"HUB_REPO: {HUB_REPO}") print(f"Model available: {MODEL is not None}") print(f"Scaler available: {SCALER is not None}") print("=" * 50) main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431"""Gradio front-end for Fault_Classification_PMU_Data models.
The application loads a CNN-LSTM model (and accompanying scaler/metadata)produced by ``fault_classification_pmu.py`` and exposes a streamlinedprediction interface optimised for Hugging Face Spaces deployment. It supportsraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""
from __future__ import annotations
import jsonimport osimport shutil
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "-1")os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0")
import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import gradio as grimport joblibimport numpy as npimport pandas as pdimport requestsfrom huggingface_hub import hf_hub_downloadfrom tensorflow.keras.models import load_model
from fault_classification_pmu import ( DEFAULT_FEATURE_COLUMNS as TRAINING_DEFAULT_FEATURE_COLUMNS, LABEL_GUESS_CANDIDATES as TRAINING_LABEL_GUESSES, train_from_dataframe,)
# --------------------------------------------------------------------------------------# Configuration# --------------------------------------------------------------------------------------DEFAULT_FEATURE_COLUMNS: List[str] = list(TRAINING_DEFAULT_FEATURE_COLUMNS)DEFAULT_SEQUENCE_LENGTH = 32DEFAULT_STRIDE = 4
LOCAL_MODEL_FILE = os.environ.get("PMU_MODEL_FILE", "pmu_cnn_lstm_model.keras")LOCAL_SCALER_FILE = os.environ.get("PMU_SCALER_FILE", "pmu_feature_scaler.pkl")LOCAL_METADATA_FILE = os.environ.get("PMU_METADATA_FILE", "pmu_metadata.json")
MODEL_OUTPUT_DIR = Path(os.environ.get("PMU_MODEL_DIR", "model")).resolve()MODEL_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
HUB_REPO = os.environ.get("PMU_HUB_REPO", "")HUB_MODEL_FILENAME = os.environ.get("PMU_HUB_MODEL_FILENAME", LOCAL_MODEL_FILE)HUB_SCALER_FILENAME = os.environ.get("PMU_HUB_SCALER_FILENAME", LOCAL_SCALER_FILE)HUB_METADATA_FILENAME = os.environ.get("PMU_HUB_METADATA_FILENAME", LOCAL_METADATA_FILE)
ENV_MODEL_PATH = "PMU_MODEL_PATH"ENV_SCALER_PATH = "PMU_SCALER_PATH"ENV_METADATA_PATH = "PMU_METADATA_PATH"
# --------------------------------------------------------------------------------------# Utility functions for loading artifacts# --------------------------------------------------------------------------------------
def download_from_hub(filename: str) -> Optional[Path]: if not HUB_REPO or not filename: return None try: print(f"Downloading {filename} from {HUB_REPO} ...") # Add timeout to prevent hanging path = hf_hub_download(repo_id=HUB_REPO, filename=filename) print("Downloaded", path) return Path(path) except Exception as exc: # pragma: no cover - logging convenience print("Failed to download", filename, "from", HUB_REPO, ":", exc) print("Continuing without pre-trained model...") return None
def resolve_artifact( local_name: str, env_var: str, hub_filename: str) -> Optional[Path]: print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}") candidates = [Path(local_name)] if local_name else [] if local_name: candidates.append(MODEL_OUTPUT_DIR / Path(local_name).name) env_value = os.environ.get(env_var) if env_value: candidates.append(Path(env_value))
for candidate in candidates: if candidate and candidate.exists(): print(f"Found local artifact: {candidate}") return candidate
print(f"No local artifacts found, checking hub...") # Only try to download if we have a hub repo configured if HUB_REPO: return download_from_hub(hub_filename) else: print("No HUB_REPO configured, skipping download") return None
def load_metadata(path: Optional[Path]) -> Dict: if path and path.exists(): try: return json.loads(path.read_text()) except Exception as exc: # pragma: no cover - metadata parsing errors print("Failed to read metadata", path, exc) return {}
def try_load_scaler(path: Optional[Path]): if not path: return None try: scaler = joblib.load(path) print("Loaded scaler from", path) return scaler except Exception as exc: print("Failed to load scaler", path, exc) return None
# Initialize paths with error handlingprint("Starting application initialization...")try: MODEL_PATH = resolve_artifact(LOCAL_MODEL_FILE, ENV_MODEL_PATH, HUB_MODEL_FILENAME) print(f"Model path resolved: {MODEL_PATH}")except Exception as e: print(f"Model path resolution failed: {e}") MODEL_PATH = None
try: SCALER_PATH = resolve_artifact( LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME ) print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e: print(f"Scaler path resolution failed: {e}") SCALER_PATH = None
try: METADATA_PATH = resolve_artifact( LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME ) print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e: print(f"Metadata path resolution failed: {e}") METADATA_PATH = None
try: METADATA = load_metadata(METADATA_PATH) print(f"Metadata loaded: {len(METADATA)} entries")except Exception as e: print(f"Metadata loading failed: {e}") METADATA = {}
# Queuing configurationQUEUE_MAX_SIZE = 32# Apply a small per-event concurrency limit to avoid relying on the deprecated# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2
def try_load_model(path: Optional[Path], model_type: str, model_format: str): if not path: return None try: if model_type == "svm" or model_format == "joblib": model = joblib.load(path) else: model = load_model(path) print("Loaded model from", path) return model except Exception as exc: # pragma: no cover - runtime diagnostics print("Failed to load model", path, exc) return None
FEATURE_COLUMNS: List[str] = list(DEFAULT_FEATURE_COLUMNS)LABEL_CLASSES: List[str] = []LABEL_COLUMN: str = "Fault"SEQUENCE_LENGTH: int = DEFAULT_SEQUENCE_LENGTHDEFAULT_WINDOW_STRIDE: int = DEFAULT_STRIDEMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"
def _model_output_path(filename: str) -> str: return str(MODEL_OUTPUT_DIR / Path(filename).name)
MODEL_FILENAME_BY_TYPE: Dict[str, str] = { "cnn_lstm": Path(LOCAL_MODEL_FILE).name, "tcn": "pmu_tcn_model.keras", "svm": "pmu_svm_model.joblib",}
REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path( os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
TRAINING_DATA_REPO = os.environ.get( "PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)
GITHUB_CONTENT_CACHE: Dict[str, List[Dict[str, Any]]] = {}
APP_CSS = """#available-files-section { position: relative; display: flex; flex-direction: column; gap: 0.75rem; border-radius: 0.75rem; isolation: isolate;}
#available-files-grid { position: static; overflow: visible;}
#available-files-grid .form { position: static; min-height: 16rem;}
#available-files-grid .wrap { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.5rem; max-height: 24rem; min-height: 16rem; overflow-y: auto; padding-right: 0.25rem;}
#available-files-grid .wrap > div { min-width: 0;}
#available-files-grid .wrap label { margin: 0; display: flex; align-items: center; padding: 0.45rem 0.65rem; border-radius: 0.65rem; background-color: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease, border-color 0.2s ease; min-height: 2.5rem;}
#available-files-grid .wrap label:hover { background-color: rgba(90, 200, 250, 0.16); border-color: rgba(90, 200, 250, 0.4);}
#available-files-grid .wrap label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
#available-files-section .gradio-loading,#available-files-grid .gradio-loading { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.92); border-radius: 0.75rem; z-index: 999; padding: 1.5rem; pointer-events: auto;}
#available-files-section .gradio-loading,#available-files-grid .gradio-loading { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.92); border-radius: 0.75rem; z-index: 999; padding: 1.5rem; pointer-events: auto;}
#available-files-section .gradio-loading > *,#available-files-grid .gradio-loading > * { width: 100%;}
#available-files-section .gradio-loading progress,#available-files-section .gradio-loading .progress-bar,#available-files-section .gradio-loading .loading-progress,#available-files-section .gradio-loading [role="progressbar"],#available-files-section .gradio-loading .wrap,#available-files-section .gradio-loading .inner,#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,#available-files-grid .gradio-loading [role="progressbar"],#available-files-grid .gradio-loading .wrap,#available-files-grid .gradio-loading .inner { width: 100% !important; max-width: none !important;}
#available-files-section .gradio-loading .status,#available-files-section .gradio-loading .message,#available-files-section .gradio-loading .label,#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label { text-align: center;}
#date-browser-row { gap: 0.75rem;}
#date-browser-row .date-browser-column { flex: 1 1 0%; min-width: 0;}
#date-browser-row .date-browser-column > .gradio-dropdown,#date-browser-row .date-browser-column > .gradio-button { width: 100%;}
#date-browser-row .date-browser-column > .gradio-dropdown > div { width: 100%;}
#date-browser-row .date-browser-column .gradio-button { justify-content: center;}
#training-files-summary textarea { max-height: 12rem; overflow-y: auto;}
#download-selected-button { width: 100%; position: relative; z-index: 0;}
#download-selected-button .gradio-button { width: 100%; justify-content: center;}
#artifact-download-row { gap: 0.75rem;}
#artifact-download-row .artifact-download-button { flex: 1 1 0%; min-width: 0;}
#artifact-download-row .artifact-download-button .gradio-button { width: 100%; justify-content: center;}"""
def _github_cache_key(path: str) -> str: return path or "__root__"
def _github_api_url(path: str) -> str: clean_path = path.strip("/") base = f"https://api.github.com/repos/{TRAINING_DATA_REPO}/contents" if clean_path: return f"{base}/{clean_path}?ref={TRAINING_DATA_BRANCH}" return f"{base}?ref={TRAINING_DATA_BRANCH}"
def list_remote_directory( path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]: key = _github_cache_key(path) if not force_refresh and key in GITHUB_CONTENT_CACHE: return GITHUB_CONTENT_CACHE[key]
url = _github_api_url(path) response = requests.get(url, timeout=30) if response.status_code != 200: raise RuntimeError( f"GitHub API request failed for `{path or '.'}` (status {response.status_code})." )
payload = response.json() if not isinstance(payload, list): raise RuntimeError( "Unexpected GitHub API payload. Expected a directory listing." )
GITHUB_CONTENT_CACHE[key] = payload return payload
def list_remote_years(force_refresh: bool = False) -> List[str]: entries = list_remote_directory("", force_refresh=force_refresh) years = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(years)
def list_remote_months(year: str, *, force_refresh: bool = False) -> List[str]: if not year: return [] entries = list_remote_directory(year, force_refresh=force_refresh) months = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(months)
def list_remote_days( year: str, month: str, *, force_refresh: bool = False) -> List[str]: if not year or not month: return [] entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh) days = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(days)
def list_remote_files( year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]: if not year or not month or not day: return [] entries = list_remote_directory( f"{year}/{month}/{day}", force_refresh=force_refresh ) files = [item["name"] for item in entries if item.get("type") == "file"] return sorted(files)
def download_repository_file(year: str, month: str, day: str, filename: str) -> Path: if not filename: raise ValueError("Filename cannot be empty when downloading repository data.")
relative_parts = [part for part in (year, month, day, filename) if part] if len(relative_parts) < 4: raise ValueError("Provide year, month, day, and filename to download a CSV.")
relative_path = "/".join(relative_parts) raw_url = ( f"https://raw.githubusercontent.com/{TRAINING_DATA_REPO}/" f"{TRAINING_DATA_BRANCH}/{relative_path}" )
response = requests.get(raw_url, stream=True, timeout=120) if response.status_code != 200: raise RuntimeError( f"Failed to download `{relative_path}` (status {response.status_code})." )
target_dir = TRAINING_DATA_DIR.joinpath(year, month, day) target_dir.mkdir(parents=True, exist_ok=True) target_path = target_dir / filename
with open(target_path, "wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): if chunk: handle.write(chunk)
return target_path
def _normalise_header(name: str) -> str: return str(name).strip().lower()
def guess_label_from_columns( columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]: if not columns: return preferred
lookup = {_normalise_header(col): str(col) for col in columns}
if preferred: preferred_stripped = preferred.strip() for col in columns: if str(col).strip() == preferred_stripped: return str(col) preferred_norm = _normalise_header(preferred) if preferred_norm in lookup: return lookup[preferred_norm]
for guess in TRAINING_LABEL_GUESSES: guess_norm = _normalise_header(guess) if guess_norm in lookup: return lookup[guess_norm]
for col in columns: if _normalise_header(col).startswith("fault"): return str(col)
return str(columns[0])
def summarise_training_files(paths: Sequence[str], notes: Sequence[str]) -> str: lines = [Path(path).name for path in paths] lines.extend(notes) return "\n".join(lines) if lines else "No training files available."
def read_training_status(status_file_path: str) -> str: """Read the current training status from file.""" try: if Path(status_file_path).exists(): with open(status_file_path, "r") as f: return f.read().strip() except Exception: pass return "Training status unavailable"
def _persist_uploaded_file(file_obj) -> Optional[Path]: if file_obj is None: return None
if isinstance(file_obj, (str, Path)): source = Path(file_obj) original_name = source.name else: source = Path(getattr(file_obj, "name", "") or getattr(file_obj, "path", "")) original_name = getattr(file_obj, "orig_name", source.name) or source.name if not source or not source.exists(): return None
original_name = Path(original_name).name or source.name
base_path = Path(original_name) destination = TRAINING_UPLOAD_DIR / base_path.name counter = 1 while destination.exists(): suffix = base_path.suffix or ".csv" destination = TRAINING_UPLOAD_DIR / f"{base_path.stem}_{counter}{suffix}" counter += 1
shutil.copy2(source, destination) return destination
def prepare_training_paths( paths: Sequence[str], current_label: str, cleanup_missing: bool = False): valid_paths: List[str] = [] notes: List[str] = [] columns_map: Dict[str, str] = {} for path in paths: try: df = load_measurement_csv(path) except Exception as exc: # pragma: no cover - user file diagnostics notes.append(f"⚠️ Skipped {Path(path).name}: {exc}") if cleanup_missing: try: Path(path).unlink(missing_ok=True) except Exception: pass continue valid_paths.append(str(path)) for col in df.columns: columns_map[_normalise_header(col)] = str(col)
summary = summarise_training_files(valid_paths, notes) preferred = current_label or LABEL_COLUMN dropdown_choices = ( sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN] ) guessed = guess_label_from_columns(dropdown_choices, preferred) dropdown_value = guessed or preferred or LABEL_COLUMN
return ( valid_paths, summary, gr.update(choices=dropdown_choices, value=dropdown_value), )
def append_training_files(new_files, existing_paths: Sequence[str], current_label: str): if isinstance(existing_paths, (str, Path)): paths: List[str] = [str(existing_paths)] elif existing_paths is None: paths = [] else: paths = list(existing_paths) if new_files: for file in new_files: persisted = _persist_uploaded_file(file) if persisted is None: continue path_str = str(persisted) if path_str not in paths: paths.append(path_str)
return prepare_training_paths(paths, current_label, cleanup_missing=True)
def load_repository_training_files(current_label: str, force_refresh: bool = False): if force_refresh: # Clearing the cache is enough because downloads are now on-demand. for cached in list(TRAINING_DATA_DIR.glob("*")): # On refresh we keep previously downloaded files; no deletion required. # The flag triggers downstream UI updates only. break
csv_paths = sorted( str(path) for path in TRAINING_DATA_DIR.rglob("*.csv") if path.is_file() ) if not csv_paths: message = ( "No local database CSVs are available yet. Use the database browser " "below to download specific days before training." ) default_label = current_label or LABEL_COLUMN or "Fault" return ( [], message, gr.update(choices=[default_label], value=default_label), message, )
valid_paths, summary, label_update = prepare_training_paths( csv_paths, current_label, cleanup_missing=False )
info = ( f"Ready with {len(valid_paths)} CSV file(s) cached locally under " f"the database cache `{TRAINING_DATA_DIR}`." )
return valid_paths, summary, label_update, info
def refresh_remote_browser(force_refresh: bool = False): if force_refresh: GITHUB_CONTENT_CACHE.clear() try: years = list_remote_years(force_refresh=force_refresh) if years: message = "Select a year, month, and day to list available CSV files." else: message = ( "⚠️ No directories were found in the database root. Verify the upstream " "structure." ) return ( gr.update(choices=years, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to query database: {exc}", )
def on_year_change(year: Optional[str]): if not year: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a year to continue.", ) try: months = list_remote_months(year) message = ( f"Year `{year}` selected. Choose a month to drill down." if months else f"⚠️ No months available under `{year}`." ) return ( gr.update(choices=months, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list months: {exc}", )
def on_month_change(year: Optional[str], month: Optional[str]): if not year or not month: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a month to continue.", ) try: days = list_remote_days(year, month) message = ( f"Month `{year}/{month}` ready. Pick a day to view files." if days else f"⚠️ No day folders found under `{year}/{month}`." ) return ( gr.update(choices=days, value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list days: {exc}", )
def on_day_change(year: Optional[str], month: Optional[str], day: Optional[str]): if not year or not month or not day: return ( gr.update(choices=[], value=[]), "Select a day to load file names.", ) try: files = list_remote_files(year, month, day) message = ( f"{len(files)} file(s) available for `{year}/{month}/{day}`." if files else f"⚠️ No CSV files found under `{year}/{month}/{day}`." ) return ( gr.update(choices=files, value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=[]), f"⚠️ Failed to list files: {exc}", )
def download_selected_files( year: Optional[str], month: Optional[str], day: Optional[str], filenames: Sequence[str], current_label: str,): if not filenames: message = "Select at least one CSV before downloading." local = load_repository_training_files(current_label) return (*local, gr.update(), message)
success: List[str] = [] notes: List[str] = [] for filename in filenames: try: path = download_repository_file( year or "", month or "", day or "", filename ) success.append(str(path)) except Exception as exc: notes.append(f"⚠️ {filename}: {exc}")
local = load_repository_training_files(current_label)
message_lines = [] if success: message_lines.append( f"Downloaded {len(success)} file(s) to the database cache `{TRAINING_DATA_DIR}`." ) if notes: message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_day_bundle( year: Optional[str], month: Optional[str], day: Optional[str], current_label: str,): if not (year and month and day): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year, month, and day before downloading an entire day.", )
try: files = list_remote_files(year, month, day) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to list CSVs for `{year}/{month}/{day}`: {exc}", )
if not files: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No CSV files were found for `{year}/{month}/{day}`.", )
result = list(download_selected_files(year, month, day, files, current_label)) result[-1] = ( f"Downloaded all {len(files)} CSV file(s) for `{year}/{month}/{day}`.\n" f"{result[-1]}" ) return tuple(result)
def download_month_bundle( year: Optional[str], month: Optional[str], current_label: str): if not (year and month): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year and month before downloading an entire month.", )
try: days = list_remote_days(year, month) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate days for `{year}/{month}`: {exc}", )
if not days: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No day folders were found for `{year}/{month}`.", )
downloaded = 0 notes: List[str] = [] for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}/{month}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_year_bundle(year: Optional[str], current_label: str): if not year: local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year before downloading an entire year of CSVs.", )
try: months = list_remote_months(year) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate months for `{year}`: {exc}", )
if not months: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No month folders were found for `{year}`.", )
downloaded = 0 notes: List[str] = [] for month in months: try: days = list_remote_days(year, month) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}`: {exc}") continue if not days: notes.append(f"⚠️ No day folders in `{year}/{month}`.") continue for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def clear_downloaded_cache(current_label: str): status_message = "" try: if TRAINING_DATA_DIR.exists(): shutil.rmtree(TRAINING_DATA_DIR) TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True) status_message = ( f"Cleared all downloaded CSVs from database cache `{TRAINING_DATA_DIR}`." ) except Exception as exc: status_message = f"⚠️ Failed to clear database cache: {exc}"
local = load_repository_training_files(current_label, force_refresh=True) remote = list(refresh_remote_browser(force_refresh=False)) if status_message: previous = remote[-1] if isinstance(previous, str) and previous: remote[-1] = f"{status_message}\n{previous}" else: remote[-1] = status_message
return (*local, *remote)
def normalise_output_directory(directory: Optional[str]) -> Path: base = Path(directory or MODEL_OUTPUT_DIR) base = base.expanduser() if not base.is_absolute(): base = (Path.cwd() / base).resolve() return base
def resolve_output_path( directory: Optional[Union[Path, str]], filename: Optional[str], fallback: str) -> Path: if isinstance(directory, Path): base = directory else: base = normalise_output_directory(directory) candidate = Path(filename or "").expanduser() if str(candidate): if candidate.is_absolute(): return candidate return (base / candidate).resolve() return (base / fallback).resolve()
ARTIFACT_FILE_EXTENSIONS: Tuple[str, ...] = ( ".keras", ".h5", ".joblib", ".pkl", ".json", ".onnx", ".zip", ".txt",)
def gather_directory_choices(current: Optional[str]) -> Tuple[List[str], str]: base = normalise_output_directory(current or str(MODEL_OUTPUT_DIR)) candidates = {str(base)} try: for candidate in base.parent.iterdir(): if candidate.is_dir(): candidates.add(str(candidate.resolve())) except Exception: pass return sorted(candidates), str(base)
def gather_artifact_choices( directory: Optional[str], selection: Optional[str] = None) -> Tuple[List[Tuple[str, str]], Optional[str]]: base = normalise_output_directory(directory) choices: List[Tuple[str, str]] = [] selected_value: Optional[str] = None if base.exists(): try: artifacts = sorted( [ path for path in base.iterdir() if path.is_file() and ( not ARTIFACT_FILE_EXTENSIONS or path.suffix.lower() in ARTIFACT_FILE_EXTENSIONS ) ], key=lambda path: path.name.lower(), ) choices = [(artifact.name, str(artifact)) for artifact in artifacts] except Exception: choices = []
if selection and any(value == selection for _, value in choices): selected_value = selection elif choices: selected_value = choices[0][1]
return choices, selected_value
def download_button_state(path: Optional[Union[str, Path]]): if not path: return gr.update(value=None, visible=False) candidate = Path(path) if candidate.exists(): return gr.update(value=str(candidate), visible=True) return gr.update(value=None, visible=False)
def clear_training_files(): default_label = LABEL_COLUMN or "Fault" for cached_file in TRAINING_UPLOAD_DIR.glob("*"): try: if cached_file.is_file(): cached_file.unlink(missing_ok=True) except Exception: pass return ( [], "No training files selected.", gr.update(choices=[default_label], value=default_label), gr.update(value=None), )
PROJECT_OVERVIEW_MD = """## Project Overview
This project focuses on classifying faults in electrical transmission lines andgrid-connected photovoltaic (PV) systems by combining ensemble learningtechniques with deep neural architectures.
## Datasets
### Transmission Line Fault Dataset- 134,406 samples collected from Phasor Measurement Units (PMUs)- 14 monitored channels covering currents, voltages, magnitudes, frequency, and phase angles- Labels span symmetrical and asymmetrical faults: NF, L-G, LL, LL-G, LLL, and LLL-G- Time span: 0 to 5.7 seconds with high-frequency sampling
### Grid-Connected PV System Fault Dataset- 2,163,480 samples from 16 experimental scenarios- 14 features including PV array measurements (Ipv, Vpv, Vdc), three-phase currents/voltages, aggregate magnitudes (Iabc, Vabc), and frequency indicators (If, Vf)- Captures array, inverter, grid anomaly, feedback sensor, and MPPT controller faults at 9.9989 μs sampling intervals
## Data Format Quick Reference
Each measurement file may be comma or tab separated and typically exposes thefollowing ordered columns:
1. `Timestamp`2. `[325] UPMU_SUB22:FREQ` – system frequency (Hz)3. `[326] UPMU_SUB22:DFDT` – frequency rate-of-change4. `[327] UPMU_SUB22:FLAG` – PMU status flag5. `[328] UPMU_SUB22-L1:MAG` – phase A voltage magnitude6. `[329] UPMU_SUB22-L1:ANG` – phase A voltage angle7. `[330] UPMU_SUB22-L2:MAG` – phase B voltage magnitude8. `[331] UPMU_SUB22-L2:ANG` – phase B voltage angle9. `[332] UPMU_SUB22-L3:MAG` – phase C voltage magnitude10. `[333] UPMU_SUB22-L3:ANG` – phase C voltage angle11. `[334] UPMU_SUB22-C1:MAG` – phase A current magnitude12. `[335] UPMU_SUB22-C1:ANG` – phase A current angle13. `[336] UPMU_SUB22-C2:MAG` – phase B current magnitude14. `[337] UPMU_SUB22-C2:ANG` – phase B current angle15. `[338] UPMU_SUB22-C3:MAG` – phase C current magnitude16. `[339] UPMU_SUB22-C3:ANG` – phase C current angle
The training tab automatically downloads the latest CSV exports from the`VincentCroft/ThesisModelData` repository and concatenates them before buildingsliding windows.
## Models Developed
1. **Support Vector Machine (SVM)** – provides the classical machine learning baseline with balanced accuracy across both datasets (85% PMU / 83% PV).2. **CNN-LSTM** – couples convolutional feature extraction with temporal memory, achieving 92% PMU / 89% PV accuracy.3. **Temporal Convolutional Network (TCN)** – leverages dilated convolutions for long-range context and delivers the best trade-off between accuracy and training time (94% PMU / 91% PV).
## Results Summary
- **Transmission Line Fault Classification**: SVM 85%, CNN-LSTM 92%, TCN 94%- **PV System Fault Classification**: SVM 83%, CNN-LSTM 89%, TCN 91%
Use the **Inference** tab to score new PMU/PV windows and the **Training** tab tofine-tune or retrain any of the supported models directly within Hugging FaceSpaces. The logs panel will surface TensorBoard archives whenever deep-learningmodels are trained."""
def load_measurement_csv(path: str) -> pd.DataFrame: """Read a PMU/PV measurement file with flexible separators and column mapping."""
try: df = pd.read_csv(path, sep=None, engine="python", encoding="utf-8-sig") except Exception: df = None for separator in ("\t", ",", ";"): try: df = pd.read_csv( path, sep=separator, engine="python", encoding="utf-8-sig" ) break except Exception: df = None if df is None: raise
# Clean column names df.columns = [str(col).strip() for col in df.columns]
print(f"Loaded CSV with {len(df)} rows and {len(df.columns)} columns") print(f"Columns: {list(df.columns)}") print(f"Data shape: {df.shape}")
# Check if we have enough data for training if len(df) < 100: print( f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training." )
# Check for label column has_label = any( col.lower() in ["fault", "label", "class", "target"] for col in df.columns ) if not has_label: print( "Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples." ) df["Fault"] = "Normal" # Add dummy label for training
# Create column mapping - map similar column names to expected format column_mapping = {} expected_cols = list(REQUIRED_PMU_COLUMNS)
# If we have at least the right number of numeric columns after Timestamp, use positional mapping if "Timestamp" in df.columns: numeric_cols = [col for col in df.columns if col != "Timestamp"] if len(numeric_cols) >= len(expected_cols): # Map by position (after Timestamp) for i, expected_col in enumerate(expected_cols): if i < len(numeric_cols): column_mapping[numeric_cols[i]] = expected_col
# Rename columns to match expected format df = df.rename(columns=column_mapping)
# Check if we have the required columns after mapping missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns] if missing: # If still missing, try a more flexible approach available_numeric = df.select_dtypes(include=[np.number]).columns.tolist() if len(available_numeric) >= len(expected_cols): # Use the first N numeric columns for i, expected_col in enumerate(expected_cols): if i < len(available_numeric): if available_numeric[i] not in df.columns: continue df = df.rename(columns={available_numeric[i]: expected_col})
# Recheck missing columns missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns]
if missing: missing_str = ", ".join(missing) available_str = ", ".join(df.columns.tolist()) raise ValueError( f"Missing required PMU feature columns: {missing_str}. " f"Available columns: {available_str}. " "Please ensure your CSV has the correct format with Timestamp followed by PMU measurements." )
return df
def apply_metadata(metadata: Dict[str, Any]) -> None: global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMAT FEATURE_COLUMNS = [ str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS) ] LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])] LABEL_COLUMN = str(metadata.get("label_column", "Fault")) SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH)) DEFAULT_WINDOW_STRIDE = int(metadata.get("stride", DEFAULT_STRIDE)) MODEL_TYPE = str(metadata.get("model_type", "cnn_lstm")).lower() MODEL_FORMAT = str( metadata.get("model_format", "joblib" if MODEL_TYPE == "svm" else "keras") ).lower()
apply_metadata(METADATA)
def sync_label_classes_from_model(model: Optional[object]) -> None: global LABEL_CLASSES if model is None: return if hasattr(model, "classes_"): LABEL_CLASSES = [str(label) for label in getattr(model, "classes_")] elif not LABEL_CLASSES and hasattr(model, "output_shape"): LABEL_CLASSES = [str(i) for i in range(int(model.output_shape[-1]))]
# Load model and scaler with error handlingprint("Loading model and scaler...")try: MODEL = try_load_model(MODEL_PATH, MODEL_TYPE, MODEL_FORMAT) print(f"Model loaded: {MODEL is not None}")except Exception as e: print(f"Model loading failed: {e}") MODEL = None
try: SCALER = try_load_scaler(SCALER_PATH) print(f"Scaler loaded: {SCALER is not None}")except Exception as e: print(f"Scaler loading failed: {e}") SCALER = None
try: sync_label_classes_from_model(MODEL) print("Label classes synchronized")except Exception as e: print(f"Label sync failed: {e}")
print("Application initialization completed.")print( f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")
def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None: global MODEL_PATH, SCALER_PATH, METADATA_PATH, MODEL, SCALER, METADATA MODEL_PATH = model_path SCALER_PATH = scaler_path METADATA_PATH = metadata_path METADATA = load_metadata(metadata_path) apply_metadata(METADATA) MODEL = try_load_model(model_path, MODEL_TYPE, MODEL_FORMAT) SCALER = try_load_scaler(scaler_path) sync_label_classes_from_model(MODEL)
# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------
def ensure_ready(): if MODEL is None or SCALER is None: raise RuntimeError( "The model and feature scaler are not available. Upload the trained model " "(for example `pmu_cnn_lstm_model.keras`, `pmu_tcn_model.keras`, or `pmu_svm_model.joblib`), " "the feature scaler (`pmu_feature_scaler.pkl`), and the metadata JSON (`pmu_metadata.json`) to the Space root " "or configure the Hugging Face Hub environment variables so the artifacts can be downloaded " "automatically." )
def parse_text_features(text: str) -> np.ndarray: cleaned = re.sub(r"[;\n\t]+", ",", text.strip()) arr = np.fromstring(cleaned, sep=",") if arr.size == 0: raise ValueError( "No feature values were parsed. Please enter comma-separated numbers." ) return arr.astype(np.float32)
def apply_scaler(sequences: np.ndarray) -> np.ndarray: if SCALER is None: return sequences shape = sequences.shape flattened = sequences.reshape(-1, shape[-1]) scaled = SCALER.transform(flattened) return scaled.reshape(shape)
def make_sliding_windows( data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray: if data.shape[0] < sequence_length: raise ValueError( f"The dataset contains {data.shape[0]} rows which is less than the requested sequence " f"length {sequence_length}. Provide more samples or reduce the sequence length." ) windows = [ data[start : start + sequence_length] for start in range(0, data.shape[0] - sequence_length + 1, stride) ] return np.stack(windows)
def dataframe_to_sequences( df: pd.DataFrame, *, sequence_length: int, stride: int, feature_columns: Sequence[str], drop_label: bool = True,) -> np.ndarray: work_df = df.copy() if drop_label and LABEL_COLUMN in work_df.columns: work_df = work_df.drop(columns=[LABEL_COLUMN]) if "Timestamp" in work_df.columns: work_df = work_df.sort_values("Timestamp")
available_cols = [c for c in feature_columns if c in work_df.columns] n_features = len(feature_columns) if available_cols and len(available_cols) == n_features: array = work_df[available_cols].astype(np.float32).to_numpy() return make_sliding_windows(array, sequence_length, stride)
numeric_df = work_df.select_dtypes(include=[np.number]) array = numeric_df.astype(np.float32).to_numpy() if array.shape[1] == n_features * sequence_length: return array.reshape(array.shape[0], sequence_length, n_features) if sequence_length == 1 and array.shape[1] == n_features: return array.reshape(array.shape[0], 1, n_features) raise ValueError( "CSV columns do not match the expected feature layout. Include the full PMU feature set " "or provide pre-shaped sliding window data." )
def label_name(index: int) -> str: if 0 <= index < len(LABEL_CLASSES): return str(LABEL_CLASSES[index]) return f"class_{index}"
def format_predictions(probabilities: np.ndarray) -> pd.DataFrame: rows: List[Dict[str, object]] = [] order = np.argsort(probabilities, axis=1)[:, ::-1] for idx, (prob_row, ranking) in enumerate(zip(probabilities, order)): top_idx = int(ranking[0]) top_label = label_name(top_idx) top_conf = float(prob_row[top_idx]) top3 = [f"{label_name(i)} ({prob_row[i]*100:.2f}%)" for i in ranking[:3]] rows.append( { "window": idx, "predicted_label": top_label, "confidence": round(top_conf, 4), "top3": " | ".join(top3), } ) return pd.DataFrame(rows)
def probabilities_to_json(probabilities: np.ndarray) -> List[Dict[str, object]]: payload: List[Dict[str, object]] = [] for idx, prob_row in enumerate(probabilities): payload.append( { "window": int(idx), "probabilities": { label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0]) }, } ) return payload
def predict_sequences( sequences: np.ndarray,) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: ensure_ready() sequences = apply_scaler(sequences.astype(np.float32)) if MODEL_TYPE == "svm": flattened = sequences.reshape(sequences.shape[0], -1) if hasattr(MODEL, "predict_proba"): probs = MODEL.predict_proba(flattened) else: raise RuntimeError( "Loaded SVM model does not expose predict_proba. Retrain with probability=True." ) else: probs = MODEL.predict(sequences, verbose=0) table = format_predictions(probs) json_probs = probabilities_to_json(probs) architecture = MODEL_TYPE.replace("_", "-").upper() status = f"Generated {len(sequences)} windows. {architecture} model output dimension: {probs.shape[1]}." return status, table, json_probs
def predict_from_text( text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: arr = parse_text_features(text) n_features = len(FEATURE_COLUMNS) if arr.size % n_features != 0: raise ValueError( f"The number of values ({arr.size}) is not a multiple of the feature dimension " f"({n_features}). Provide values in groups of {n_features}." ) timesteps = arr.size // n_features if timesteps != sequence_length: raise ValueError( f"Detected {timesteps} timesteps which does not match the configured sequence length " f"({sequence_length})." ) sequences = arr.reshape(1, sequence_length, n_features) status, table, probs = predict_sequences(sequences) status = f"Single window prediction complete. {status}" return status, table, probs
def predict_from_csv( file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: df = load_measurement_csv(file_obj.name) sequences = dataframe_to_sequences( df, sequence_length=sequence_length, stride=stride, feature_columns=FEATURE_COLUMNS, ) status, table, probs = predict_sequences(sequences) status = f"CSV processed successfully. Generated {len(sequences)} windows. {status}" return status, table, probs
# --------------------------------------------------------------------------------------# Training helpers# --------------------------------------------------------------------------------------
def classification_report_to_dataframe(report: Dict[str, Any]) -> pd.DataFrame: rows: List[Dict[str, Any]] = [] for label, metrics in report.items(): if isinstance(metrics, dict): row = {"label": label} for key, value in metrics.items(): if key == "support": row[key] = int(value) else: row[key] = round(float(value), 4) rows.append(row) else: rows.append({"label": label, "accuracy": round(float(metrics), 4)}) return pd.DataFrame(rows)
def confusion_matrix_to_dataframe( confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame: if not confusion: return pd.DataFrame() df = pd.DataFrame(confusion, index=list(labels), columns=list(labels)) df.index.name = "True Label" df.columns.name = "Predicted Label" return df
# --------------------------------------------------------------------------------------# Gradio interface# --------------------------------------------------------------------------------------
def build_interface() -> gr.Blocks: theme = gr.themes.Soft( primary_hue="sky", secondary_hue="blue", neutral_hue="gray" ).set( body_background_fill="#1f1f1f", body_text_color="#f5f5f5", block_background_fill="#262626", block_border_color="#333333", button_primary_background_fill="#5ac8fa", button_primary_background_fill_hover="#48b5eb", button_primary_border_color="#38bdf8", button_primary_text_color="#0f172a", button_secondary_background_fill="#3f3f46", button_secondary_text_color="#f5f5f5", )
def _normalise_directory_string(value: Optional[Union[str, Path]]) -> str: if value is None: return "" path = Path(value).expanduser() try: return str(path.resolve()) except Exception: return str(path)
with gr.Blocks( title="Fault Classification - PMU Data", theme=theme, css=APP_CSS ) as demo: gr.Markdown("# Fault Classification for PMU & PV Data") gr.Markdown( "🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers." ) if MODEL is None or SCALER is None: gr.Markdown( "⚠️ **Artifacts Missing** — Upload `pmu_cnn_lstm_model.keras`, " "`pmu_feature_scaler.pkl`, and `pmu_metadata.json` to enable inference, " "or configure the Hugging Face Hub environment variables so they can be downloaded." ) else: class_count = len(LABEL_CLASSES) if LABEL_CLASSES else "unknown" gr.Markdown( f"Loaded a **{MODEL_TYPE.upper()}** model ({MODEL_FORMAT.upper()}) with " f"{len(FEATURE_COLUMNS)} features, sequence length **{SEQUENCE_LENGTH}**, and " f"{class_count} target classes. Use the tabs below to run inference or fine-tune " "the model with your own CSV files." )
with gr.Accordion("Feature Reference", open=False): gr.Markdown( f"Each time window expects **{len(FEATURE_COLUMNS)} features** ordered as follows:\n" + "\n".join(f"- {name}" for name in FEATURE_COLUMNS) ) gr.Markdown( f"Default training parameters: **sequence length = {SEQUENCE_LENGTH}**, " f"**stride = {DEFAULT_WINDOW_STRIDE}**. Adjust them in the tabs as needed." )
with gr.Tabs(): with gr.Tab("Overview"): gr.Markdown(PROJECT_OVERVIEW_MD) with gr.Tab("Inference"): gr.Markdown("## Run Inference") with gr.Row(): file_in = gr.File(label="Upload PMU CSV", file_types=[".csv"]) text_in = gr.Textbox( lines=4, label="Or paste a single window (comma separated)", placeholder="49.97772,1.215825E-38,...", )
with gr.Row(): sequence_length_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length (timesteps)", ) stride_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="CSV window stride", )
predict_btn = gr.Button("🚀 Run Inference", variant="primary") status_out = gr.Textbox(label="Status", interactive=False) table_out = gr.Dataframe( headers=["window", "predicted_label", "confidence", "top3"], label="Predictions", interactive=False, ) probs_out = gr.JSON(label="Per-window probabilities")
def _run_prediction(file_obj, text, sequence_length, stride): sequence_length = int(sequence_length) stride = int(stride) try: if file_obj is not None: return predict_from_csv(file_obj, sequence_length, stride) if text and text.strip(): return predict_from_text(text, sequence_length) return ( "Please upload a CSV file or provide feature values.", pd.DataFrame(), [], ) except Exception as exc: return f"Prediction failed: {exc}", pd.DataFrame(), []
predict_btn.click( _run_prediction, inputs=[file_in, text_in, sequence_length_input, stride_input], outputs=[status_out, table_out, probs_out], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Tab("Training"): gr.Markdown("## Train or Fine-tune the Model") gr.Markdown( "Training data is automatically downloaded from the database. " "Refresh the cache if new files are added upstream." )
training_files_state = gr.State([]) with gr.Row(): with gr.Column(scale=3): training_files_summary = gr.Textbox( label="Database training CSVs", value="Training dataset not loaded yet.", lines=4, interactive=False, elem_id="training-files-summary", ) with gr.Column(scale=2, min_width=240): dataset_info = gr.Markdown( "No local database CSVs downloaded yet.", ) dataset_refresh = gr.Button( "🔄 Reload dataset from database", variant="secondary", ) clear_cache_button = gr.Button( "🧹 Clear downloaded cache", variant="secondary", )
with gr.Accordion("📂 DataBaseBrowser", open=False): gr.Markdown( "Browse the upstream database by date and download only the CSVs you need." ) with gr.Row(elem_id="date-browser-row"): with gr.Column(scale=1, elem_classes=["date-browser-column"]): year_selector = gr.Dropdown(label="Year", choices=[]) year_download_button = gr.Button( "⬇️ Download year CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): month_selector = gr.Dropdown(label="Month", choices=[]) month_download_button = gr.Button( "⬇️ Download month CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): day_selector = gr.Dropdown(label="Day", choices=[]) day_download_button = gr.Button( "⬇️ Download day CSVs", variant="secondary" ) with gr.Column(elem_id="available-files-section"): available_files = gr.CheckboxGroup( label="Available CSV files", choices=[], value=[], elem_id="available-files-grid", ) download_button = gr.Button( "⬇️ Download selected CSVs", variant="secondary", elem_id="download-selected-button", ) repo_status = gr.Markdown( "Click 'Reload dataset from database' to fetch the directory tree." )
with gr.Row(): label_input = gr.Dropdown( value=LABEL_COLUMN, choices=[LABEL_COLUMN], allow_custom_value=True, label="Label column name", ) model_selector = gr.Radio( choices=["CNN-LSTM", "TCN", "SVM"], value=( "TCN" if MODEL_TYPE == "tcn" else ("SVM" if MODEL_TYPE == "svm" else "CNN-LSTM") ), label="Model architecture", ) sequence_length_train = gr.Slider( minimum=4, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length", ) stride_train = gr.Slider( minimum=1, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="Stride", )
model_default = MODEL_FILENAME_BY_TYPE.get( MODEL_TYPE, Path(LOCAL_MODEL_FILE).name )
with gr.Row(): validation_train = gr.Slider( minimum=0.05, maximum=0.4, step=0.05, value=0.2, label="Validation split", ) batch_train = gr.Slider( minimum=32, maximum=512, step=32, value=128, label="Batch size", ) epochs_train = gr.Slider( minimum=5, maximum=100, step=5, value=50, label="Epochs", )
directory_choices, directory_default = gather_directory_choices( str(MODEL_OUTPUT_DIR) ) artifact_choices, default_artifact = gather_artifact_choices( directory_default )
with gr.Row(): output_directory = gr.Dropdown( value=directory_default, label="Output directory", choices=directory_choices, allow_custom_value=True, ) model_name = gr.Textbox( value=model_default, label="Model output filename", ) scaler_name = gr.Textbox( value=Path(LOCAL_SCALER_FILE).name, label="Scaler output filename", ) metadata_name = gr.Textbox( value=Path(LOCAL_METADATA_FILE).name, label="Metadata output filename", )
with gr.Row(): artifact_browser = gr.Dropdown( label="Saved artifacts in directory", choices=artifact_choices, value=default_artifact, ) artifact_download_button = gr.DownloadButton( "⬇️ Download selected artifact", value=default_artifact, visible=bool(default_artifact), variant="secondary", )
def on_output_directory_change(selected_dir, current_selection): choices, normalised = gather_directory_choices(selected_dir) artifact_options, selected = gather_artifact_choices( normalised, current_selection ) return ( gr.update(choices=choices, value=normalised), gr.update(choices=artifact_options, value=selected), download_button_state(selected), )
def on_artifact_change(selected_path): return download_button_state(selected_path)
output_directory.change( on_output_directory_change, inputs=[output_directory, artifact_browser], outputs=[ output_directory, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
artifact_browser.change( on_artifact_change, inputs=[artifact_browser], outputs=[artifact_download_button], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Row(elem_id="artifact-download-row"): model_download_button = gr.DownloadButton( "⬇️ Download model file", value=None, visible=False, elem_classes=["artifact-download-button"], ) scaler_download_button = gr.DownloadButton( "⬇️ Download scaler file", value=None, visible=False, elem_classes=["artifact-download-button"], ) metadata_download_button = gr.DownloadButton( "⬇️ Download metadata file", value=None, visible=False, elem_classes=["artifact-download-button"], ) tensorboard_download_button = gr.DownloadButton( "⬇️ Download TensorBoard logs", value=None, visible=False, elem_classes=["artifact-download-button"], )
model_download_button.file_name = Path(LOCAL_MODEL_FILE).name scaler_download_button.file_name = Path(LOCAL_SCALER_FILE).name metadata_download_button.file_name = Path(LOCAL_METADATA_FILE).name tensorboard_download_button.file_name = "tensorboard_logs.zip"
tensorboard_toggle = gr.Checkbox( value=True, label="Enable TensorBoard logging (creates downloadable archive)", )
def _suggest_model_filename(choice: str, current_value: str): choice_key = (choice or "cnn_lstm").lower().replace("-", "_") suggested = MODEL_FILENAME_BY_TYPE.get( choice_key, Path(LOCAL_MODEL_FILE).name ) known_defaults = set(MODEL_FILENAME_BY_TYPE.values()) current_name = Path(current_value).name if current_value else "" if current_name and current_name not in known_defaults: return gr.update() return gr.update(value=suggested)
model_selector.change( _suggest_model_filename, inputs=[model_selector, model_name], outputs=model_name, )
with gr.Row(): train_button = gr.Button("🛠️ Start Training", variant="primary") progress_button = gr.Button( "📊 Check Progress", variant="secondary" )
# Training status display training_status = gr.Textbox(label="Training Status", interactive=False) report_output = gr.Dataframe( label="Classification report", interactive=False ) history_output = gr.JSON(label="Training history") confusion_output = gr.Dataframe( label="Confusion matrix", interactive=False )
# Message area at the bottom for progress updates with gr.Accordion("📋 Progress Messages", open=True): progress_messages = gr.Textbox( label="Training Messages", lines=8, max_lines=20, interactive=False, autoscroll=True, placeholder="Click 'Check Progress' to see training updates...", ) with gr.Row(): gr.Button("🗑️ Clear Messages", variant="secondary").click( lambda: "", outputs=[progress_messages] )
def _run_training( file_paths, label_column, model_choice, sequence_length, stride, validation_split, batch_size, epochs, output_dir, model_filename, scaler_filename, metadata_filename, enable_tensorboard, ): base_dir = normalise_output_directory(output_dir) try: base_dir.mkdir(parents=True, exist_ok=True)
model_path = resolve_output_path( base_dir, model_filename, Path(LOCAL_MODEL_FILE).name, ) scaler_path = resolve_output_path( base_dir, scaler_filename, Path(LOCAL_SCALER_FILE).name, ) metadata_path = resolve_output_path( base_dir, metadata_filename, Path(LOCAL_METADATA_FILE).name, )
model_path.parent.mkdir(parents=True, exist_ok=True) scaler_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True)
# Create status file path for progress tracking status_file = model_path.parent / "training_status.txt"
# Initialize status with open(status_file, "w") as f: f.write("Starting training setup...")
if not file_paths: raise ValueError( "No training CSVs were found in the database cache. " "Use 'Reload dataset from database' and try again." )
with open(status_file, "w") as f: f.write("Loading and validating CSV files...")
available_paths = [ path for path in file_paths if Path(path).exists() ] missing_paths = [ Path(path).name for path in file_paths if not Path(path).exists() ] if not available_paths: raise ValueError( "Database training dataset is unavailable. Reload the dataset and retry." )
dfs = [load_measurement_csv(path) for path in available_paths] combined = pd.concat(dfs, ignore_index=True)
# Validate data size and provide recommendations total_samples = len(combined) if total_samples < 100: print( f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results." ) print( "Automatically switching to SVM for small dataset compatibility." ) if model_choice in ["cnn_lstm", "tcn"]: model_choice = "svm" print( f"Model type changed to SVM for better small dataset performance." ) if total_samples < 10: raise ValueError( f"Insufficient data: {total_samples} samples. Need at least 10 samples for training." )
label_column = (label_column or LABEL_COLUMN).strip() if not label_column: raise ValueError("Label column name cannot be empty.")
model_choice = ( (model_choice or "CNN-LSTM").lower().replace("-", "_") ) if model_choice not in {"cnn_lstm", "tcn", "svm"}: raise ValueError( "Select CNN-LSTM, TCN, or SVM for the model architecture." )
with open(status_file, "w") as f: f.write( f"Starting {model_choice.upper()} training with {len(combined)} samples..." )
# Start training result = train_from_dataframe( combined, label_column=label_column, feature_columns=None, sequence_length=int(sequence_length), stride=int(stride), validation_split=float(validation_split), batch_size=int(batch_size), epochs=int(epochs), model_type=model_choice, model_path=model_path, scaler_path=scaler_path, metadata_path=metadata_path, enable_tensorboard=bool(enable_tensorboard), )
refresh_artifacts( Path(result["model_path"]), Path(result["scaler_path"]), Path(result["metadata_path"]), )
report_df = classification_report_to_dataframe( result["classification_report"] ) confusion_df = confusion_matrix_to_dataframe( result["confusion_matrix"], result["class_names"] ) tensorboard_dir = result.get("tensorboard_log_dir") tensorboard_zip = result.get("tensorboard_zip_path")
architecture = result["model_type"].replace("_", "-").upper() status = ( f"Training complete using a {architecture} architecture. " f"{result['num_sequences']} windows derived from " f"{result['num_samples']} rows across {len(available_paths)} file(s)." f" Artifacts saved to:" f"\n• Model: {result['model_path']}\n" f"• Scaler: {result['scaler_path']}\n" f"• Metadata: {result['metadata_path']}" )
status += f"\nLabel column used: {result.get('label_column', label_column)}"
if tensorboard_dir: status += ( f"\nTensorBoard logs directory: {tensorboard_dir}" f'\nRun `tensorboard --logdir "{tensorboard_dir}"` to inspect the training curves.' "\nDownload the archive below to explore the run offline." )
if missing_paths: skipped = ", ".join(missing_paths) status = f"⚠️ Skipped missing files: {skipped}\n" + status
artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir), result["model_path"] )
return ( status, report_df, result["history"], confusion_df, download_button_state(result["model_path"]), download_button_state(result["scaler_path"]), download_button_state(result["metadata_path"]), download_button_state(tensorboard_zip), gr.update(value=result.get("label_column", label_column)), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), ) except Exception as exc: artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir) ) return ( f"Training failed: {exc}", pd.DataFrame(), {}, pd.DataFrame(), download_button_state(None), download_button_state(None), download_button_state(None), download_button_state(None), gr.update(), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), )
def _check_progress(output_dir, model_filename, current_messages): """Check training progress by reading status file and accumulate messages.""" model_path = resolve_output_path( output_dir, model_filename, Path(LOCAL_MODEL_FILE).name ) status_file = model_path.parent / "training_status.txt" status_message = read_training_status(str(status_file))
# Add timestamp to the message from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S") new_message = f"[{timestamp}] {status_message}"
# Accumulate messages, keeping last 50 lines to prevent overflow if current_messages: lines = current_messages.split("\n") lines.append(new_message) # Keep only last 50 lines if len(lines) > 50: lines = lines[-50:] accumulated_messages = "\n".join(lines) else: accumulated_messages = new_message
return accumulated_messages
train_button.click( _run_training, inputs=[ training_files_state, label_input, model_selector, sequence_length_train, stride_train, validation_train, batch_train, epochs_train, output_directory, model_name, scaler_name, metadata_name, tensorboard_toggle, ], outputs=[ training_status, report_output, history_output, confusion_output, model_download_button, scaler_download_button, metadata_download_button, tensorboard_download_button, label_input, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
progress_button.click( _check_progress, inputs=[output_directory, model_name, progress_messages], outputs=[progress_messages], )
year_selector.change( on_year_change, inputs=[year_selector], outputs=[ month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_selector.change( on_month_change, inputs=[year_selector, month_selector], outputs=[day_selector, available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_selector.change( on_day_change, inputs=[year_selector, month_selector, day_selector], outputs=[available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
download_button.click( download_selected_files, inputs=[ year_selector, month_selector, day_selector, available_files, label_input, ], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
year_download_button.click( download_year_bundle, inputs=[year_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_download_button.click( download_month_bundle, inputs=[year_selector, month_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_download_button.click( download_day_bundle, inputs=[year_selector, month_selector, day_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _reload_dataset(current_label): local = load_repository_training_files( current_label, force_refresh=True ) remote = refresh_remote_browser(force_refresh=True) return (*local, *remote)
dataset_refresh.click( _reload_dataset, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
clear_cache_button.click( clear_downloaded_cache, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _initialise_dataset(): local = load_repository_training_files( LABEL_COLUMN, force_refresh=False ) remote = refresh_remote_browser(force_refresh=False) return (*local, *remote)
demo.load( _initialise_dataset, inputs=None, outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], queue=False, )
return demo
# --------------------------------------------------------------------------------------# Launch helpers# --------------------------------------------------------------------------------------
def resolve_server_port() -> int: for env_var in ("PORT", "GRADIO_SERVER_PORT"): value = os.environ.get(env_var) if value: try: return int(value) except ValueError: print(f"Ignoring invalid port value from {env_var}: {value}") return 7860
def main(): print("Building Gradio interface...") try: demo = build_interface() print("Interface built successfully") except Exception as e: print(f"Failed to build interface: {e}") import traceback
traceback.print_exc() return
print("Setting up queue...") try: demo.queue(max_size=QUEUE_MAX_SIZE) print("Queue configured") except Exception as e: print(f"Failed to configure queue: {e}")
try: port = resolve_server_port() print(f"Launching Gradio app on port {port}") demo.launch(server_name="0.0.0.0", server_port=port, show_error=True) except OSError as exc: print("Failed to launch on requested port:", exc) try: demo.launch(server_name="0.0.0.0", show_error=True) except Exception as e: print(f"Failed to launch completely: {e}") except Exception as e: print(f"Unexpected launch error: {e}") import traceback
traceback.print_exc()
if __name__ == "__main__": print("=" * 50) print("PMU Fault Classification App Starting") print(f"Python version: {os.sys.version}") print(f"Working directory: {os.getcwd()}") print(f"HUB_REPO: {HUB_REPO}") print(f"Model available: {MODEL is not None}") print(f"Scaler available: {SCALER is not None}") print("=" * 50) main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431"""Gradio front-end for Fault_Classification_PMU_Data models.
The application loads a CNN-LSTM model (and accompanying scaler/metadata)produced by ``fault_classification_pmu.py`` and exposes a streamlinedprediction interface optimised for Hugging Face Spaces deployment. It supportsraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""
from __future__ import annotations
import jsonimport osimport shutil
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "-1")os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0")
import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import gradio as grimport joblibimport numpy as npimport pandas as pdimport requestsfrom huggingface_hub import hf_hub_downloadfrom tensorflow.keras.models import load_model
from fault_classification_pmu import ( DEFAULT_FEATURE_COLUMNS as TRAINING_DEFAULT_FEATURE_COLUMNS, LABEL_GUESS_CANDIDATES as TRAINING_LABEL_GUESSES, train_from_dataframe,)
# --------------------------------------------------------------------------------------# Configuration# --------------------------------------------------------------------------------------DEFAULT_FEATURE_COLUMNS: List[str] = list(TRAINING_DEFAULT_FEATURE_COLUMNS)DEFAULT_SEQUENCE_LENGTH = 32DEFAULT_STRIDE = 4
LOCAL_MODEL_FILE = os.environ.get("PMU_MODEL_FILE", "pmu_cnn_lstm_model.keras")LOCAL_SCALER_FILE = os.environ.get("PMU_SCALER_FILE", "pmu_feature_scaler.pkl")LOCAL_METADATA_FILE = os.environ.get("PMU_METADATA_FILE", "pmu_metadata.json")
MODEL_OUTPUT_DIR = Path(os.environ.get("PMU_MODEL_DIR", "model")).resolve()MODEL_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
HUB_REPO = os.environ.get("PMU_HUB_REPO", "")HUB_MODEL_FILENAME = os.environ.get("PMU_HUB_MODEL_FILENAME", LOCAL_MODEL_FILE)HUB_SCALER_FILENAME = os.environ.get("PMU_HUB_SCALER_FILENAME", LOCAL_SCALER_FILE)HUB_METADATA_FILENAME = os.environ.get("PMU_HUB_METADATA_FILENAME", LOCAL_METADATA_FILE)
ENV_MODEL_PATH = "PMU_MODEL_PATH"ENV_SCALER_PATH = "PMU_SCALER_PATH"ENV_METADATA_PATH = "PMU_METADATA_PATH"
# --------------------------------------------------------------------------------------# Utility functions for loading artifacts# --------------------------------------------------------------------------------------
def download_from_hub(filename: str) -> Optional[Path]: if not HUB_REPO or not filename: return None try: print(f"Downloading {filename} from {HUB_REPO} ...") # Add timeout to prevent hanging path = hf_hub_download(repo_id=HUB_REPO, filename=filename) print("Downloaded", path) return Path(path) except Exception as exc: # pragma: no cover - logging convenience print("Failed to download", filename, "from", HUB_REPO, ":", exc) print("Continuing without pre-trained model...") return None
def resolve_artifact( local_name: str, env_var: str, hub_filename: str) -> Optional[Path]: print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}") candidates = [Path(local_name)] if local_name else [] if local_name: candidates.append(MODEL_OUTPUT_DIR / Path(local_name).name) env_value = os.environ.get(env_var) if env_value: candidates.append(Path(env_value))
for candidate in candidates: if candidate and candidate.exists(): print(f"Found local artifact: {candidate}") return candidate
print(f"No local artifacts found, checking hub...") # Only try to download if we have a hub repo configured if HUB_REPO: return download_from_hub(hub_filename) else: print("No HUB_REPO configured, skipping download") return None
def load_metadata(path: Optional[Path]) -> Dict: if path and path.exists(): try: return json.loads(path.read_text()) except Exception as exc: # pragma: no cover - metadata parsing errors print("Failed to read metadata", path, exc) return {}
def try_load_scaler(path: Optional[Path]): if not path: return None try: scaler = joblib.load(path) print("Loaded scaler from", path) return scaler except Exception as exc: print("Failed to load scaler", path, exc) return None
# Initialize paths with error handlingprint("Starting application initialization...")try: MODEL_PATH = resolve_artifact(LOCAL_MODEL_FILE, ENV_MODEL_PATH, HUB_MODEL_FILENAME) print(f"Model path resolved: {MODEL_PATH}")except Exception as e: print(f"Model path resolution failed: {e}") MODEL_PATH = None
try: SCALER_PATH = resolve_artifact( LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME ) print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e: print(f"Scaler path resolution failed: {e}") SCALER_PATH = None
try: METADATA_PATH = resolve_artifact( LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME ) print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e: print(f"Metadata path resolution failed: {e}") METADATA_PATH = None
try: METADATA = load_metadata(METADATA_PATH) print(f"Metadata loaded: {len(METADATA)} entries")except Exception as e: print(f"Metadata loading failed: {e}") METADATA = {}
# Queuing configurationQUEUE_MAX_SIZE = 32# Apply a small per-event concurrency limit to avoid relying on the deprecated# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2
def try_load_model(path: Optional[Path], model_type: str, model_format: str): if not path: return None try: if model_type == "svm" or model_format == "joblib": model = joblib.load(path) else: model = load_model(path) print("Loaded model from", path) return model except Exception as exc: # pragma: no cover - runtime diagnostics print("Failed to load model", path, exc) return None
FEATURE_COLUMNS: List[str] = list(DEFAULT_FEATURE_COLUMNS)LABEL_CLASSES: List[str] = []LABEL_COLUMN: str = "Fault"SEQUENCE_LENGTH: int = DEFAULT_SEQUENCE_LENGTHDEFAULT_WINDOW_STRIDE: int = DEFAULT_STRIDEMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"
def _model_output_path(filename: str) -> str: return str(MODEL_OUTPUT_DIR / Path(filename).name)
MODEL_FILENAME_BY_TYPE: Dict[str, str] = { "cnn_lstm": Path(LOCAL_MODEL_FILE).name, "tcn": "pmu_tcn_model.keras", "svm": "pmu_svm_model.joblib",}
REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path( os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
TRAINING_DATA_REPO = os.environ.get( "PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)
GITHUB_CONTENT_CACHE: Dict[str, List[Dict[str, Any]]] = {}
APP_CSS = """#available-files-section { position: relative; display: flex; flex-direction: column; gap: 0.75rem; border-radius: 0.75rem; isolation: isolate;}
#available-files-grid { position: static; overflow: visible;}
#available-files-grid .form { position: static; min-height: 16rem;}
#available-files-grid .wrap { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.5rem; max-height: 24rem; min-height: 16rem; overflow-y: auto; padding-right: 0.25rem;}
#available-files-grid .wrap > div { min-width: 0;}
#available-files-grid .wrap label { margin: 0; display: flex; align-items: center; padding: 0.45rem 0.65rem; border-radius: 0.65rem; background-color: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease, border-color 0.2s ease; min-height: 2.5rem;}
#available-files-grid .wrap label:hover { background-color: rgba(90, 200, 250, 0.16); border-color: rgba(90, 200, 250, 0.4);}
#available-files-grid .wrap label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
#available-files-section .gradio-loading,#available-files-grid .gradio-loading { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.92); border-radius: 0.75rem; z-index: 999; padding: 1.5rem; pointer-events: auto;}
#available-files-section .gradio-loading,#available-files-grid .gradio-loading { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: rgba(10, 14, 23, 0.92); border-radius: 0.75rem; z-index: 999; padding: 1.5rem; pointer-events: auto;}
#available-files-section .gradio-loading > *,#available-files-grid .gradio-loading > * { width: 100%;}
#available-files-section .gradio-loading progress,#available-files-section .gradio-loading .progress-bar,#available-files-section .gradio-loading .loading-progress,#available-files-section .gradio-loading [role="progressbar"],#available-files-section .gradio-loading .wrap,#available-files-section .gradio-loading .inner,#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,#available-files-grid .gradio-loading [role="progressbar"],#available-files-grid .gradio-loading .wrap,#available-files-grid .gradio-loading .inner { width: 100% !important; max-width: none !important;}
#available-files-section .gradio-loading .status,#available-files-section .gradio-loading .message,#available-files-section .gradio-loading .label,#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label { text-align: center;}
#date-browser-row { gap: 0.75rem;}
#date-browser-row .date-browser-column { flex: 1 1 0%; min-width: 0;}
#date-browser-row .date-browser-column > .gradio-dropdown,#date-browser-row .date-browser-column > .gradio-button { width: 100%;}
#date-browser-row .date-browser-column > .gradio-dropdown > div { width: 100%;}
#date-browser-row .date-browser-column .gradio-button { justify-content: center;}
#training-files-summary textarea { max-height: 12rem; overflow-y: auto;}
#download-selected-button { width: 100%; position: relative; z-index: 0;}
#download-selected-button .gradio-button { width: 100%; justify-content: center;}
#artifact-download-row { gap: 0.75rem;}
#artifact-download-row .artifact-download-button { flex: 1 1 0%; min-width: 0;}
#artifact-download-row .artifact-download-button .gradio-button { width: 100%; justify-content: center;}"""
def _github_cache_key(path: str) -> str: return path or "__root__"
def _github_api_url(path: str) -> str: clean_path = path.strip("/") base = f"https://api.github.com/repos/{TRAINING_DATA_REPO}/contents" if clean_path: return f"{base}/{clean_path}?ref={TRAINING_DATA_BRANCH}" return f"{base}?ref={TRAINING_DATA_BRANCH}"
def list_remote_directory( path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]: key = _github_cache_key(path) if not force_refresh and key in GITHUB_CONTENT_CACHE: return GITHUB_CONTENT_CACHE[key]
url = _github_api_url(path) response = requests.get(url, timeout=30) if response.status_code != 200: raise RuntimeError( f"GitHub API request failed for `{path or '.'}` (status {response.status_code})." )
payload = response.json() if not isinstance(payload, list): raise RuntimeError( "Unexpected GitHub API payload. Expected a directory listing." )
GITHUB_CONTENT_CACHE[key] = payload return payload
def list_remote_years(force_refresh: bool = False) -> List[str]: entries = list_remote_directory("", force_refresh=force_refresh) years = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(years)
def list_remote_months(year: str, *, force_refresh: bool = False) -> List[str]: if not year: return [] entries = list_remote_directory(year, force_refresh=force_refresh) months = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(months)
def list_remote_days( year: str, month: str, *, force_refresh: bool = False) -> List[str]: if not year or not month: return [] entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh) days = [item["name"] for item in entries if item.get("type") == "dir"] return sorted(days)
def list_remote_files( year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]: if not year or not month or not day: return [] entries = list_remote_directory( f"{year}/{month}/{day}", force_refresh=force_refresh ) files = [item["name"] for item in entries if item.get("type") == "file"] return sorted(files)
def download_repository_file(year: str, month: str, day: str, filename: str) -> Path: if not filename: raise ValueError("Filename cannot be empty when downloading repository data.")
relative_parts = [part for part in (year, month, day, filename) if part] if len(relative_parts) < 4: raise ValueError("Provide year, month, day, and filename to download a CSV.")
relative_path = "/".join(relative_parts) raw_url = ( f"https://raw.githubusercontent.com/{TRAINING_DATA_REPO}/" f"{TRAINING_DATA_BRANCH}/{relative_path}" )
response = requests.get(raw_url, stream=True, timeout=120) if response.status_code != 200: raise RuntimeError( f"Failed to download `{relative_path}` (status {response.status_code})." )
target_dir = TRAINING_DATA_DIR.joinpath(year, month, day) target_dir.mkdir(parents=True, exist_ok=True) target_path = target_dir / filename
with open(target_path, "wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): if chunk: handle.write(chunk)
return target_path
def _normalise_header(name: str) -> str: return str(name).strip().lower()
def guess_label_from_columns( columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]: if not columns: return preferred
lookup = {_normalise_header(col): str(col) for col in columns}
if preferred: preferred_stripped = preferred.strip() for col in columns: if str(col).strip() == preferred_stripped: return str(col) preferred_norm = _normalise_header(preferred) if preferred_norm in lookup: return lookup[preferred_norm]
for guess in TRAINING_LABEL_GUESSES: guess_norm = _normalise_header(guess) if guess_norm in lookup: return lookup[guess_norm]
for col in columns: if _normalise_header(col).startswith("fault"): return str(col)
return str(columns[0])
def summarise_training_files(paths: Sequence[str], notes: Sequence[str]) -> str: lines = [Path(path).name for path in paths] lines.extend(notes) return "\n".join(lines) if lines else "No training files available."
def read_training_status(status_file_path: str) -> str: """Read the current training status from file.""" try: if Path(status_file_path).exists(): with open(status_file_path, "r") as f: return f.read().strip() except Exception: pass return "Training status unavailable"
def _persist_uploaded_file(file_obj) -> Optional[Path]: if file_obj is None: return None
if isinstance(file_obj, (str, Path)): source = Path(file_obj) original_name = source.name else: source = Path(getattr(file_obj, "name", "") or getattr(file_obj, "path", "")) original_name = getattr(file_obj, "orig_name", source.name) or source.name if not source or not source.exists(): return None
original_name = Path(original_name).name or source.name
base_path = Path(original_name) destination = TRAINING_UPLOAD_DIR / base_path.name counter = 1 while destination.exists(): suffix = base_path.suffix or ".csv" destination = TRAINING_UPLOAD_DIR / f"{base_path.stem}_{counter}{suffix}" counter += 1
shutil.copy2(source, destination) return destination
def prepare_training_paths( paths: Sequence[str], current_label: str, cleanup_missing: bool = False): valid_paths: List[str] = [] notes: List[str] = [] columns_map: Dict[str, str] = {} for path in paths: try: df = load_measurement_csv(path) except Exception as exc: # pragma: no cover - user file diagnostics notes.append(f"⚠️ Skipped {Path(path).name}: {exc}") if cleanup_missing: try: Path(path).unlink(missing_ok=True) except Exception: pass continue valid_paths.append(str(path)) for col in df.columns: columns_map[_normalise_header(col)] = str(col)
summary = summarise_training_files(valid_paths, notes) preferred = current_label or LABEL_COLUMN dropdown_choices = ( sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN] ) guessed = guess_label_from_columns(dropdown_choices, preferred) dropdown_value = guessed or preferred or LABEL_COLUMN
return ( valid_paths, summary, gr.update(choices=dropdown_choices, value=dropdown_value), )
def append_training_files(new_files, existing_paths: Sequence[str], current_label: str): if isinstance(existing_paths, (str, Path)): paths: List[str] = [str(existing_paths)] elif existing_paths is None: paths = [] else: paths = list(existing_paths) if new_files: for file in new_files: persisted = _persist_uploaded_file(file) if persisted is None: continue path_str = str(persisted) if path_str not in paths: paths.append(path_str)
return prepare_training_paths(paths, current_label, cleanup_missing=True)
def load_repository_training_files(current_label: str, force_refresh: bool = False): if force_refresh: # Clearing the cache is enough because downloads are now on-demand. for cached in list(TRAINING_DATA_DIR.glob("*")): # On refresh we keep previously downloaded files; no deletion required. # The flag triggers downstream UI updates only. break
csv_paths = sorted( str(path) for path in TRAINING_DATA_DIR.rglob("*.csv") if path.is_file() ) if not csv_paths: message = ( "No local database CSVs are available yet. Use the database browser " "below to download specific days before training." ) default_label = current_label or LABEL_COLUMN or "Fault" return ( [], message, gr.update(choices=[default_label], value=default_label), message, )
valid_paths, summary, label_update = prepare_training_paths( csv_paths, current_label, cleanup_missing=False )
info = ( f"Ready with {len(valid_paths)} CSV file(s) cached locally under " f"the database cache `{TRAINING_DATA_DIR}`." )
return valid_paths, summary, label_update, info
def refresh_remote_browser(force_refresh: bool = False): if force_refresh: GITHUB_CONTENT_CACHE.clear() try: years = list_remote_years(force_refresh=force_refresh) if years: message = "Select a year, month, and day to list available CSV files." else: message = ( "⚠️ No directories were found in the database root. Verify the upstream " "structure." ) return ( gr.update(choices=years, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to query database: {exc}", )
def on_year_change(year: Optional[str]): if not year: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a year to continue.", ) try: months = list_remote_months(year) message = ( f"Year `{year}` selected. Choose a month to drill down." if months else f"⚠️ No months available under `{year}`." ) return ( gr.update(choices=months, value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list months: {exc}", )
def on_month_change(year: Optional[str], month: Optional[str]): if not year or not month: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), "Select a month to continue.", ) try: days = list_remote_days(year, month) message = ( f"Month `{year}/{month}` ready. Pick a day to view files." if days else f"⚠️ No day folders found under `{year}/{month}`." ) return ( gr.update(choices=days, value=None), gr.update(choices=[], value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=[]), f"⚠️ Failed to list days: {exc}", )
def on_day_change(year: Optional[str], month: Optional[str], day: Optional[str]): if not year or not month or not day: return ( gr.update(choices=[], value=[]), "Select a day to load file names.", ) try: files = list_remote_files(year, month, day) message = ( f"{len(files)} file(s) available for `{year}/{month}/{day}`." if files else f"⚠️ No CSV files found under `{year}/{month}/{day}`." ) return ( gr.update(choices=files, value=[]), message, ) except Exception as exc: return ( gr.update(choices=[], value=[]), f"⚠️ Failed to list files: {exc}", )
def download_selected_files( year: Optional[str], month: Optional[str], day: Optional[str], filenames: Sequence[str], current_label: str,): if not filenames: message = "Select at least one CSV before downloading." local = load_repository_training_files(current_label) return (*local, gr.update(), message)
success: List[str] = [] notes: List[str] = [] for filename in filenames: try: path = download_repository_file( year or "", month or "", day or "", filename ) success.append(str(path)) except Exception as exc: notes.append(f"⚠️ {filename}: {exc}")
local = load_repository_training_files(current_label)
message_lines = [] if success: message_lines.append( f"Downloaded {len(success)} file(s) to the database cache `{TRAINING_DATA_DIR}`." ) if notes: message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_day_bundle( year: Optional[str], month: Optional[str], day: Optional[str], current_label: str,): if not (year and month and day): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year, month, and day before downloading an entire day.", )
try: files = list_remote_files(year, month, day) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to list CSVs for `{year}/{month}/{day}`: {exc}", )
if not files: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No CSV files were found for `{year}/{month}/{day}`.", )
result = list(download_selected_files(year, month, day, files, current_label)) result[-1] = ( f"Downloaded all {len(files)} CSV file(s) for `{year}/{month}/{day}`.\n" f"{result[-1]}" ) return tuple(result)
def download_month_bundle( year: Optional[str], month: Optional[str], current_label: str): if not (year and month): local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year and month before downloading an entire month.", )
try: days = list_remote_days(year, month) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate days for `{year}/{month}`: {exc}", )
if not days: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No day folders were found for `{year}/{month}`.", )
downloaded = 0 notes: List[str] = [] for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}/{month}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def download_year_bundle(year: Optional[str], current_label: str): if not year: local = load_repository_training_files(current_label) return ( *local, gr.update(), "Select a year before downloading an entire year of CSVs.", )
try: months = list_remote_months(year) except Exception as exc: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"⚠️ Failed to enumerate months for `{year}`: {exc}", )
if not months: local = load_repository_training_files(current_label) return ( *local, gr.update(), f"No month folders were found for `{year}`.", )
downloaded = 0 notes: List[str] = [] for month in months: try: days = list_remote_days(year, month) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}`: {exc}") continue if not days: notes.append(f"⚠️ No day folders in `{year}/{month}`.") continue for day in days: try: files = list_remote_files(year, month, day) except Exception as exc: notes.append(f"⚠️ Failed to list `{year}/{month}/{day}`: {exc}") continue if not files: notes.append(f"⚠️ No CSV files in `{year}/{month}/{day}`.") continue for filename in files: try: download_repository_file(year, month, day, filename) downloaded += 1 except Exception as exc: notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")
local = load_repository_training_files(current_label) message_lines = [] if downloaded: message_lines.append( f"Downloaded {downloaded} CSV file(s) for `{year}` into the " f"database cache `{TRAINING_DATA_DIR}`." ) message_lines.extend(notes) if not message_lines: message_lines.append("No files were downloaded.")
return (*local, gr.update(value=[]), "\n".join(message_lines))
def clear_downloaded_cache(current_label: str): status_message = "" try: if TRAINING_DATA_DIR.exists(): shutil.rmtree(TRAINING_DATA_DIR) TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True) status_message = ( f"Cleared all downloaded CSVs from database cache `{TRAINING_DATA_DIR}`." ) except Exception as exc: status_message = f"⚠️ Failed to clear database cache: {exc}"
local = load_repository_training_files(current_label, force_refresh=True) remote = list(refresh_remote_browser(force_refresh=False)) if status_message: previous = remote[-1] if isinstance(previous, str) and previous: remote[-1] = f"{status_message}\n{previous}" else: remote[-1] = status_message
return (*local, *remote)
def normalise_output_directory(directory: Optional[str]) -> Path: base = Path(directory or MODEL_OUTPUT_DIR) base = base.expanduser() if not base.is_absolute(): base = (Path.cwd() / base).resolve() return base
def resolve_output_path( directory: Optional[Union[Path, str]], filename: Optional[str], fallback: str) -> Path: if isinstance(directory, Path): base = directory else: base = normalise_output_directory(directory) candidate = Path(filename or "").expanduser() if str(candidate): if candidate.is_absolute(): return candidate return (base / candidate).resolve() return (base / fallback).resolve()
ARTIFACT_FILE_EXTENSIONS: Tuple[str, ...] = ( ".keras", ".h5", ".joblib", ".pkl", ".json", ".onnx", ".zip", ".txt",)
def gather_directory_choices(current: Optional[str]) -> Tuple[List[str], str]: base = normalise_output_directory(current or str(MODEL_OUTPUT_DIR)) candidates = {str(base)} try: for candidate in base.parent.iterdir(): if candidate.is_dir(): candidates.add(str(candidate.resolve())) except Exception: pass return sorted(candidates), str(base)
def gather_artifact_choices( directory: Optional[str], selection: Optional[str] = None) -> Tuple[List[Tuple[str, str]], Optional[str]]: base = normalise_output_directory(directory) choices: List[Tuple[str, str]] = [] selected_value: Optional[str] = None if base.exists(): try: artifacts = sorted( [ path for path in base.iterdir() if path.is_file() and ( not ARTIFACT_FILE_EXTENSIONS or path.suffix.lower() in ARTIFACT_FILE_EXTENSIONS ) ], key=lambda path: path.name.lower(), ) choices = [(artifact.name, str(artifact)) for artifact in artifacts] except Exception: choices = []
if selection and any(value == selection for _, value in choices): selected_value = selection elif choices: selected_value = choices[0][1]
return choices, selected_value
def download_button_state(path: Optional[Union[str, Path]]): if not path: return gr.update(value=None, visible=False) candidate = Path(path) if candidate.exists(): return gr.update(value=str(candidate), visible=True) return gr.update(value=None, visible=False)
def clear_training_files(): default_label = LABEL_COLUMN or "Fault" for cached_file in TRAINING_UPLOAD_DIR.glob("*"): try: if cached_file.is_file(): cached_file.unlink(missing_ok=True) except Exception: pass return ( [], "No training files selected.", gr.update(choices=[default_label], value=default_label), gr.update(value=None), )
PROJECT_OVERVIEW_MD = """## Project Overview
This project focuses on classifying faults in electrical transmission lines andgrid-connected photovoltaic (PV) systems by combining ensemble learningtechniques with deep neural architectures.
## Datasets
### Transmission Line Fault Dataset- 134,406 samples collected from Phasor Measurement Units (PMUs)- 14 monitored channels covering currents, voltages, magnitudes, frequency, and phase angles- Labels span symmetrical and asymmetrical faults: NF, L-G, LL, LL-G, LLL, and LLL-G- Time span: 0 to 5.7 seconds with high-frequency sampling
### Grid-Connected PV System Fault Dataset- 2,163,480 samples from 16 experimental scenarios- 14 features including PV array measurements (Ipv, Vpv, Vdc), three-phase currents/voltages, aggregate magnitudes (Iabc, Vabc), and frequency indicators (If, Vf)- Captures array, inverter, grid anomaly, feedback sensor, and MPPT controller faults at 9.9989 μs sampling intervals
## Data Format Quick Reference
Each measurement file may be comma or tab separated and typically exposes thefollowing ordered columns:
1. `Timestamp`2. `[325] UPMU_SUB22:FREQ` – system frequency (Hz)3. `[326] UPMU_SUB22:DFDT` – frequency rate-of-change4. `[327] UPMU_SUB22:FLAG` – PMU status flag5. `[328] UPMU_SUB22-L1:MAG` – phase A voltage magnitude6. `[329] UPMU_SUB22-L1:ANG` – phase A voltage angle7. `[330] UPMU_SUB22-L2:MAG` – phase B voltage magnitude8. `[331] UPMU_SUB22-L2:ANG` – phase B voltage angle9. `[332] UPMU_SUB22-L3:MAG` – phase C voltage magnitude10. `[333] UPMU_SUB22-L3:ANG` – phase C voltage angle11. `[334] UPMU_SUB22-C1:MAG` – phase A current magnitude12. `[335] UPMU_SUB22-C1:ANG` – phase A current angle13. `[336] UPMU_SUB22-C2:MAG` – phase B current magnitude14. `[337] UPMU_SUB22-C2:ANG` – phase B current angle15. `[338] UPMU_SUB22-C3:MAG` – phase C current magnitude16. `[339] UPMU_SUB22-C3:ANG` – phase C current angle
The training tab automatically downloads the latest CSV exports from the`VincentCroft/ThesisModelData` repository and concatenates them before buildingsliding windows.
## Models Developed
1. **Support Vector Machine (SVM)** – provides the classical machine learning baseline with balanced accuracy across both datasets (85% PMU / 83% PV).2. **CNN-LSTM** – couples convolutional feature extraction with temporal memory, achieving 92% PMU / 89% PV accuracy.3. **Temporal Convolutional Network (TCN)** – leverages dilated convolutions for long-range context and delivers the best trade-off between accuracy and training time (94% PMU / 91% PV).
## Results Summary
- **Transmission Line Fault Classification**: SVM 85%, CNN-LSTM 92%, TCN 94%- **PV System Fault Classification**: SVM 83%, CNN-LSTM 89%, TCN 91%
Use the **Inference** tab to score new PMU/PV windows and the **Training** tab tofine-tune or retrain any of the supported models directly within Hugging FaceSpaces. The logs panel will surface TensorBoard archives whenever deep-learningmodels are trained."""
def load_measurement_csv(path: str) -> pd.DataFrame: """Read a PMU/PV measurement file with flexible separators and column mapping."""
try: df = pd.read_csv(path, sep=None, engine="python", encoding="utf-8-sig") except Exception: df = None for separator in ("\t", ",", ";"): try: df = pd.read_csv( path, sep=separator, engine="python", encoding="utf-8-sig" ) break except Exception: df = None if df is None: raise
# Clean column names df.columns = [str(col).strip() for col in df.columns]
print(f"Loaded CSV with {len(df)} rows and {len(df.columns)} columns") print(f"Columns: {list(df.columns)}") print(f"Data shape: {df.shape}")
# Check if we have enough data for training if len(df) < 100: print( f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training." )
# Check for label column has_label = any( col.lower() in ["fault", "label", "class", "target"] for col in df.columns ) if not has_label: print( "Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples." ) df["Fault"] = "Normal" # Add dummy label for training
# Create column mapping - map similar column names to expected format column_mapping = {} expected_cols = list(REQUIRED_PMU_COLUMNS)
# If we have at least the right number of numeric columns after Timestamp, use positional mapping if "Timestamp" in df.columns: numeric_cols = [col for col in df.columns if col != "Timestamp"] if len(numeric_cols) >= len(expected_cols): # Map by position (after Timestamp) for i, expected_col in enumerate(expected_cols): if i < len(numeric_cols): column_mapping[numeric_cols[i]] = expected_col
# Rename columns to match expected format df = df.rename(columns=column_mapping)
# Check if we have the required columns after mapping missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns] if missing: # If still missing, try a more flexible approach available_numeric = df.select_dtypes(include=[np.number]).columns.tolist() if len(available_numeric) >= len(expected_cols): # Use the first N numeric columns for i, expected_col in enumerate(expected_cols): if i < len(available_numeric): if available_numeric[i] not in df.columns: continue df = df.rename(columns={available_numeric[i]: expected_col})
# Recheck missing columns missing = [col for col in REQUIRED_PMU_COLUMNS if col not in df.columns]
if missing: missing_str = ", ".join(missing) available_str = ", ".join(df.columns.tolist()) raise ValueError( f"Missing required PMU feature columns: {missing_str}. " f"Available columns: {available_str}. " "Please ensure your CSV has the correct format with Timestamp followed by PMU measurements." )
return df
def apply_metadata(metadata: Dict[str, Any]) -> None: global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMAT FEATURE_COLUMNS = [ str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS) ] LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])] LABEL_COLUMN = str(metadata.get("label_column", "Fault")) SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH)) DEFAULT_WINDOW_STRIDE = int(metadata.get("stride", DEFAULT_STRIDE)) MODEL_TYPE = str(metadata.get("model_type", "cnn_lstm")).lower() MODEL_FORMAT = str( metadata.get("model_format", "joblib" if MODEL_TYPE == "svm" else "keras") ).lower()
apply_metadata(METADATA)
def sync_label_classes_from_model(model: Optional[object]) -> None: global LABEL_CLASSES if model is None: return if hasattr(model, "classes_"): LABEL_CLASSES = [str(label) for label in getattr(model, "classes_")] elif not LABEL_CLASSES and hasattr(model, "output_shape"): LABEL_CLASSES = [str(i) for i in range(int(model.output_shape[-1]))]
# Load model and scaler with error handlingprint("Loading model and scaler...")try: MODEL = try_load_model(MODEL_PATH, MODEL_TYPE, MODEL_FORMAT) print(f"Model loaded: {MODEL is not None}")except Exception as e: print(f"Model loading failed: {e}") MODEL = None
try: SCALER = try_load_scaler(SCALER_PATH) print(f"Scaler loaded: {SCALER is not None}")except Exception as e: print(f"Scaler loading failed: {e}") SCALER = None
try: sync_label_classes_from_model(MODEL) print("Label classes synchronized")except Exception as e: print(f"Label sync failed: {e}")
print("Application initialization completed.")print( f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")
def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None: global MODEL_PATH, SCALER_PATH, METADATA_PATH, MODEL, SCALER, METADATA MODEL_PATH = model_path SCALER_PATH = scaler_path METADATA_PATH = metadata_path METADATA = load_metadata(metadata_path) apply_metadata(METADATA) MODEL = try_load_model(model_path, MODEL_TYPE, MODEL_FORMAT) SCALER = try_load_scaler(scaler_path) sync_label_classes_from_model(MODEL)
# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------
def ensure_ready(): if MODEL is None or SCALER is None: raise RuntimeError( "The model and feature scaler are not available. Upload the trained model " "(for example `pmu_cnn_lstm_model.keras`, `pmu_tcn_model.keras`, or `pmu_svm_model.joblib`), " "the feature scaler (`pmu_feature_scaler.pkl`), and the metadata JSON (`pmu_metadata.json`) to the Space root " "or configure the Hugging Face Hub environment variables so the artifacts can be downloaded " "automatically." )
def parse_text_features(text: str) -> np.ndarray: cleaned = re.sub(r"[;\n\t]+", ",", text.strip()) arr = np.fromstring(cleaned, sep=",") if arr.size == 0: raise ValueError( "No feature values were parsed. Please enter comma-separated numbers." ) return arr.astype(np.float32)
def apply_scaler(sequences: np.ndarray) -> np.ndarray: if SCALER is None: return sequences shape = sequences.shape flattened = sequences.reshape(-1, shape[-1]) scaled = SCALER.transform(flattened) return scaled.reshape(shape)
def make_sliding_windows( data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray: if data.shape[0] < sequence_length: raise ValueError( f"The dataset contains {data.shape[0]} rows which is less than the requested sequence " f"length {sequence_length}. Provide more samples or reduce the sequence length." ) windows = [ data[start : start + sequence_length] for start in range(0, data.shape[0] - sequence_length + 1, stride) ] return np.stack(windows)
def dataframe_to_sequences( df: pd.DataFrame, *, sequence_length: int, stride: int, feature_columns: Sequence[str], drop_label: bool = True,) -> np.ndarray: work_df = df.copy() if drop_label and LABEL_COLUMN in work_df.columns: work_df = work_df.drop(columns=[LABEL_COLUMN]) if "Timestamp" in work_df.columns: work_df = work_df.sort_values("Timestamp")
available_cols = [c for c in feature_columns if c in work_df.columns] n_features = len(feature_columns) if available_cols and len(available_cols) == n_features: array = work_df[available_cols].astype(np.float32).to_numpy() return make_sliding_windows(array, sequence_length, stride)
numeric_df = work_df.select_dtypes(include=[np.number]) array = numeric_df.astype(np.float32).to_numpy() if array.shape[1] == n_features * sequence_length: return array.reshape(array.shape[0], sequence_length, n_features) if sequence_length == 1 and array.shape[1] == n_features: return array.reshape(array.shape[0], 1, n_features) raise ValueError( "CSV columns do not match the expected feature layout. Include the full PMU feature set " "or provide pre-shaped sliding window data." )
def label_name(index: int) -> str: if 0 <= index < len(LABEL_CLASSES): return str(LABEL_CLASSES[index]) return f"class_{index}"
def format_predictions(probabilities: np.ndarray) -> pd.DataFrame: rows: List[Dict[str, object]] = [] order = np.argsort(probabilities, axis=1)[:, ::-1] for idx, (prob_row, ranking) in enumerate(zip(probabilities, order)): top_idx = int(ranking[0]) top_label = label_name(top_idx) top_conf = float(prob_row[top_idx]) top3 = [f"{label_name(i)} ({prob_row[i]*100:.2f}%)" for i in ranking[:3]] rows.append( { "window": idx, "predicted_label": top_label, "confidence": round(top_conf, 4), "top3": " | ".join(top3), } ) return pd.DataFrame(rows)
def probabilities_to_json(probabilities: np.ndarray) -> List[Dict[str, object]]: payload: List[Dict[str, object]] = [] for idx, prob_row in enumerate(probabilities): payload.append( { "window": int(idx), "probabilities": { label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0]) }, } ) return payload
def predict_sequences( sequences: np.ndarray,) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: ensure_ready() sequences = apply_scaler(sequences.astype(np.float32)) if MODEL_TYPE == "svm": flattened = sequences.reshape(sequences.shape[0], -1) if hasattr(MODEL, "predict_proba"): probs = MODEL.predict_proba(flattened) else: raise RuntimeError( "Loaded SVM model does not expose predict_proba. Retrain with probability=True." ) else: probs = MODEL.predict(sequences, verbose=0) table = format_predictions(probs) json_probs = probabilities_to_json(probs) architecture = MODEL_TYPE.replace("_", "-").upper() status = f"Generated {len(sequences)} windows. {architecture} model output dimension: {probs.shape[1]}." return status, table, json_probs
def predict_from_text( text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: arr = parse_text_features(text) n_features = len(FEATURE_COLUMNS) if arr.size % n_features != 0: raise ValueError( f"The number of values ({arr.size}) is not a multiple of the feature dimension " f"({n_features}). Provide values in groups of {n_features}." ) timesteps = arr.size // n_features if timesteps != sequence_length: raise ValueError( f"Detected {timesteps} timesteps which does not match the configured sequence length " f"({sequence_length})." ) sequences = arr.reshape(1, sequence_length, n_features) status, table, probs = predict_sequences(sequences) status = f"Single window prediction complete. {status}" return status, table, probs
def predict_from_csv( file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]: df = load_measurement_csv(file_obj.name) sequences = dataframe_to_sequences( df, sequence_length=sequence_length, stride=stride, feature_columns=FEATURE_COLUMNS, ) status, table, probs = predict_sequences(sequences) status = f"CSV processed successfully. Generated {len(sequences)} windows. {status}" return status, table, probs
# --------------------------------------------------------------------------------------# Training helpers# --------------------------------------------------------------------------------------
def classification_report_to_dataframe(report: Dict[str, Any]) -> pd.DataFrame: rows: List[Dict[str, Any]] = [] for label, metrics in report.items(): if isinstance(metrics, dict): row = {"label": label} for key, value in metrics.items(): if key == "support": row[key] = int(value) else: row[key] = round(float(value), 4) rows.append(row) else: rows.append({"label": label, "accuracy": round(float(metrics), 4)}) return pd.DataFrame(rows)
def confusion_matrix_to_dataframe( confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame: if not confusion: return pd.DataFrame() df = pd.DataFrame(confusion, index=list(labels), columns=list(labels)) df.index.name = "True Label" df.columns.name = "Predicted Label" return df
# --------------------------------------------------------------------------------------# Gradio interface# --------------------------------------------------------------------------------------
def build_interface() -> gr.Blocks: theme = gr.themes.Soft( primary_hue="sky", secondary_hue="blue", neutral_hue="gray" ).set( body_background_fill="#1f1f1f", body_text_color="#f5f5f5", block_background_fill="#262626", block_border_color="#333333", button_primary_background_fill="#5ac8fa", button_primary_background_fill_hover="#48b5eb", button_primary_border_color="#38bdf8", button_primary_text_color="#0f172a", button_secondary_background_fill="#3f3f46", button_secondary_text_color="#f5f5f5", )
def _normalise_directory_string(value: Optional[Union[str, Path]]) -> str: if value is None: return "" path = Path(value).expanduser() try: return str(path.resolve()) except Exception: return str(path)
with gr.Blocks( title="Fault Classification - PMU Data", theme=theme, css=APP_CSS ) as demo: gr.Markdown("# Fault Classification for PMU & PV Data") gr.Markdown( "🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers." ) if MODEL is None or SCALER is None: gr.Markdown( "⚠️ **Artifacts Missing** — Upload `pmu_cnn_lstm_model.keras`, " "`pmu_feature_scaler.pkl`, and `pmu_metadata.json` to enable inference, " "or configure the Hugging Face Hub environment variables so they can be downloaded." ) else: class_count = len(LABEL_CLASSES) if LABEL_CLASSES else "unknown" gr.Markdown( f"Loaded a **{MODEL_TYPE.upper()}** model ({MODEL_FORMAT.upper()}) with " f"{len(FEATURE_COLUMNS)} features, sequence length **{SEQUENCE_LENGTH}**, and " f"{class_count} target classes. Use the tabs below to run inference or fine-tune " "the model with your own CSV files." )
with gr.Accordion("Feature Reference", open=False): gr.Markdown( f"Each time window expects **{len(FEATURE_COLUMNS)} features** ordered as follows:\n" + "\n".join(f"- {name}" for name in FEATURE_COLUMNS) ) gr.Markdown( f"Default training parameters: **sequence length = {SEQUENCE_LENGTH}**, " f"**stride = {DEFAULT_WINDOW_STRIDE}**. Adjust them in the tabs as needed." )
with gr.Tabs(): with gr.Tab("Overview"): gr.Markdown(PROJECT_OVERVIEW_MD) with gr.Tab("Inference"): gr.Markdown("## Run Inference") with gr.Row(): file_in = gr.File(label="Upload PMU CSV", file_types=[".csv"]) text_in = gr.Textbox( lines=4, label="Or paste a single window (comma separated)", placeholder="49.97772,1.215825E-38,...", )
with gr.Row(): sequence_length_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length (timesteps)", ) stride_input = gr.Slider( minimum=1, maximum=max(1, SEQUENCE_LENGTH), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="CSV window stride", )
predict_btn = gr.Button("🚀 Run Inference", variant="primary") status_out = gr.Textbox(label="Status", interactive=False) table_out = gr.Dataframe( headers=["window", "predicted_label", "confidence", "top3"], label="Predictions", interactive=False, ) probs_out = gr.JSON(label="Per-window probabilities")
def _run_prediction(file_obj, text, sequence_length, stride): sequence_length = int(sequence_length) stride = int(stride) try: if file_obj is not None: return predict_from_csv(file_obj, sequence_length, stride) if text and text.strip(): return predict_from_text(text, sequence_length) return ( "Please upload a CSV file or provide feature values.", pd.DataFrame(), [], ) except Exception as exc: return f"Prediction failed: {exc}", pd.DataFrame(), []
predict_btn.click( _run_prediction, inputs=[file_in, text_in, sequence_length_input, stride_input], outputs=[status_out, table_out, probs_out], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Tab("Training"): gr.Markdown("## Train or Fine-tune the Model") gr.Markdown( "Training data is automatically downloaded from the database. " "Refresh the cache if new files are added upstream." )
training_files_state = gr.State([]) with gr.Row(): with gr.Column(scale=3): training_files_summary = gr.Textbox( label="Database training CSVs", value="Training dataset not loaded yet.", lines=4, interactive=False, elem_id="training-files-summary", ) with gr.Column(scale=2, min_width=240): dataset_info = gr.Markdown( "No local database CSVs downloaded yet.", ) dataset_refresh = gr.Button( "🔄 Reload dataset from database", variant="secondary", ) clear_cache_button = gr.Button( "🧹 Clear downloaded cache", variant="secondary", )
with gr.Accordion("📂 DataBaseBrowser", open=False): gr.Markdown( "Browse the upstream database by date and download only the CSVs you need." ) with gr.Row(elem_id="date-browser-row"): with gr.Column(scale=1, elem_classes=["date-browser-column"]): year_selector = gr.Dropdown(label="Year", choices=[]) year_download_button = gr.Button( "⬇️ Download year CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): month_selector = gr.Dropdown(label="Month", choices=[]) month_download_button = gr.Button( "⬇️ Download month CSVs", variant="secondary" ) with gr.Column(scale=1, elem_classes=["date-browser-column"]): day_selector = gr.Dropdown(label="Day", choices=[]) day_download_button = gr.Button( "⬇️ Download day CSVs", variant="secondary" ) with gr.Column(elem_id="available-files-section"): available_files = gr.CheckboxGroup( label="Available CSV files", choices=[], value=[], elem_id="available-files-grid", ) download_button = gr.Button( "⬇️ Download selected CSVs", variant="secondary", elem_id="download-selected-button", ) repo_status = gr.Markdown( "Click 'Reload dataset from database' to fetch the directory tree." )
with gr.Row(): label_input = gr.Dropdown( value=LABEL_COLUMN, choices=[LABEL_COLUMN], allow_custom_value=True, label="Label column name", ) model_selector = gr.Radio( choices=["CNN-LSTM", "TCN", "SVM"], value=( "TCN" if MODEL_TYPE == "tcn" else ("SVM" if MODEL_TYPE == "svm" else "CNN-LSTM") ), label="Model architecture", ) sequence_length_train = gr.Slider( minimum=4, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=SEQUENCE_LENGTH, label="Sequence length", ) stride_train = gr.Slider( minimum=1, maximum=max(32, SEQUENCE_LENGTH * 2), step=1, value=max(1, DEFAULT_WINDOW_STRIDE), label="Stride", )
model_default = MODEL_FILENAME_BY_TYPE.get( MODEL_TYPE, Path(LOCAL_MODEL_FILE).name )
with gr.Row(): validation_train = gr.Slider( minimum=0.05, maximum=0.4, step=0.05, value=0.2, label="Validation split", ) batch_train = gr.Slider( minimum=32, maximum=512, step=32, value=128, label="Batch size", ) epochs_train = gr.Slider( minimum=5, maximum=100, step=5, value=50, label="Epochs", )
directory_choices, directory_default = gather_directory_choices( str(MODEL_OUTPUT_DIR) ) artifact_choices, default_artifact = gather_artifact_choices( directory_default )
with gr.Row(): output_directory = gr.Dropdown( value=directory_default, label="Output directory", choices=directory_choices, allow_custom_value=True, ) model_name = gr.Textbox( value=model_default, label="Model output filename", ) scaler_name = gr.Textbox( value=Path(LOCAL_SCALER_FILE).name, label="Scaler output filename", ) metadata_name = gr.Textbox( value=Path(LOCAL_METADATA_FILE).name, label="Metadata output filename", )
with gr.Row(): artifact_browser = gr.Dropdown( label="Saved artifacts in directory", choices=artifact_choices, value=default_artifact, ) artifact_download_button = gr.DownloadButton( "⬇️ Download selected artifact", value=default_artifact, visible=bool(default_artifact), variant="secondary", )
def on_output_directory_change(selected_dir, current_selection): choices, normalised = gather_directory_choices(selected_dir) artifact_options, selected = gather_artifact_choices( normalised, current_selection ) return ( gr.update(choices=choices, value=normalised), gr.update(choices=artifact_options, value=selected), download_button_state(selected), )
def on_artifact_change(selected_path): return download_button_state(selected_path)
output_directory.change( on_output_directory_change, inputs=[output_directory, artifact_browser], outputs=[ output_directory, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
artifact_browser.change( on_artifact_change, inputs=[artifact_browser], outputs=[artifact_download_button], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
with gr.Row(elem_id="artifact-download-row"): model_download_button = gr.DownloadButton( "⬇️ Download model file", value=None, visible=False, elem_classes=["artifact-download-button"], ) scaler_download_button = gr.DownloadButton( "⬇️ Download scaler file", value=None, visible=False, elem_classes=["artifact-download-button"], ) metadata_download_button = gr.DownloadButton( "⬇️ Download metadata file", value=None, visible=False, elem_classes=["artifact-download-button"], ) tensorboard_download_button = gr.DownloadButton( "⬇️ Download TensorBoard logs", value=None, visible=False, elem_classes=["artifact-download-button"], )
model_download_button.file_name = Path(LOCAL_MODEL_FILE).name scaler_download_button.file_name = Path(LOCAL_SCALER_FILE).name metadata_download_button.file_name = Path(LOCAL_METADATA_FILE).name tensorboard_download_button.file_name = "tensorboard_logs.zip"
tensorboard_toggle = gr.Checkbox( value=True, label="Enable TensorBoard logging (creates downloadable archive)", )
def _suggest_model_filename(choice: str, current_value: str): choice_key = (choice or "cnn_lstm").lower().replace("-", "_") suggested = MODEL_FILENAME_BY_TYPE.get( choice_key, Path(LOCAL_MODEL_FILE).name ) known_defaults = set(MODEL_FILENAME_BY_TYPE.values()) current_name = Path(current_value).name if current_value else "" if current_name and current_name not in known_defaults: return gr.update() return gr.update(value=suggested)
model_selector.change( _suggest_model_filename, inputs=[model_selector, model_name], outputs=model_name, )
with gr.Row(): train_button = gr.Button("🛠️ Start Training", variant="primary") progress_button = gr.Button( "📊 Check Progress", variant="secondary" )
# Training status display training_status = gr.Textbox(label="Training Status", interactive=False) report_output = gr.Dataframe( label="Classification report", interactive=False ) history_output = gr.JSON(label="Training history") confusion_output = gr.Dataframe( label="Confusion matrix", interactive=False )
# Message area at the bottom for progress updates with gr.Accordion("📋 Progress Messages", open=True): progress_messages = gr.Textbox( label="Training Messages", lines=8, max_lines=20, interactive=False, autoscroll=True, placeholder="Click 'Check Progress' to see training updates...", ) with gr.Row(): gr.Button("🗑️ Clear Messages", variant="secondary").click( lambda: "", outputs=[progress_messages] )
def _run_training( file_paths, label_column, model_choice, sequence_length, stride, validation_split, batch_size, epochs, output_dir, model_filename, scaler_filename, metadata_filename, enable_tensorboard, ): base_dir = normalise_output_directory(output_dir) try: base_dir.mkdir(parents=True, exist_ok=True)
model_path = resolve_output_path( base_dir, model_filename, Path(LOCAL_MODEL_FILE).name, ) scaler_path = resolve_output_path( base_dir, scaler_filename, Path(LOCAL_SCALER_FILE).name, ) metadata_path = resolve_output_path( base_dir, metadata_filename, Path(LOCAL_METADATA_FILE).name, )
model_path.parent.mkdir(parents=True, exist_ok=True) scaler_path.parent.mkdir(parents=True, exist_ok=True) metadata_path.parent.mkdir(parents=True, exist_ok=True)
# Create status file path for progress tracking status_file = model_path.parent / "training_status.txt"
# Initialize status with open(status_file, "w") as f: f.write("Starting training setup...")
if not file_paths: raise ValueError( "No training CSVs were found in the database cache. " "Use 'Reload dataset from database' and try again." )
with open(status_file, "w") as f: f.write("Loading and validating CSV files...")
available_paths = [ path for path in file_paths if Path(path).exists() ] missing_paths = [ Path(path).name for path in file_paths if not Path(path).exists() ] if not available_paths: raise ValueError( "Database training dataset is unavailable. Reload the dataset and retry." )
dfs = [load_measurement_csv(path) for path in available_paths] combined = pd.concat(dfs, ignore_index=True)
# Validate data size and provide recommendations total_samples = len(combined) if total_samples < 100: print( f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results." ) print( "Automatically switching to SVM for small dataset compatibility." ) if model_choice in ["cnn_lstm", "tcn"]: model_choice = "svm" print( f"Model type changed to SVM for better small dataset performance." ) if total_samples < 10: raise ValueError( f"Insufficient data: {total_samples} samples. Need at least 10 samples for training." )
label_column = (label_column or LABEL_COLUMN).strip() if not label_column: raise ValueError("Label column name cannot be empty.")
model_choice = ( (model_choice or "CNN-LSTM").lower().replace("-", "_") ) if model_choice not in {"cnn_lstm", "tcn", "svm"}: raise ValueError( "Select CNN-LSTM, TCN, or SVM for the model architecture." )
with open(status_file, "w") as f: f.write( f"Starting {model_choice.upper()} training with {len(combined)} samples..." )
# Start training result = train_from_dataframe( combined, label_column=label_column, feature_columns=None, sequence_length=int(sequence_length), stride=int(stride), validation_split=float(validation_split), batch_size=int(batch_size), epochs=int(epochs), model_type=model_choice, model_path=model_path, scaler_path=scaler_path, metadata_path=metadata_path, enable_tensorboard=bool(enable_tensorboard), )
refresh_artifacts( Path(result["model_path"]), Path(result["scaler_path"]), Path(result["metadata_path"]), )
report_df = classification_report_to_dataframe( result["classification_report"] ) confusion_df = confusion_matrix_to_dataframe( result["confusion_matrix"], result["class_names"] ) tensorboard_dir = result.get("tensorboard_log_dir") tensorboard_zip = result.get("tensorboard_zip_path")
architecture = result["model_type"].replace("_", "-").upper() status = ( f"Training complete using a {architecture} architecture. " f"{result['num_sequences']} windows derived from " f"{result['num_samples']} rows across {len(available_paths)} file(s)." f" Artifacts saved to:" f"\n• Model: {result['model_path']}\n" f"• Scaler: {result['scaler_path']}\n" f"• Metadata: {result['metadata_path']}" )
status += f"\nLabel column used: {result.get('label_column', label_column)}"
if tensorboard_dir: status += ( f"\nTensorBoard logs directory: {tensorboard_dir}" f'\nRun `tensorboard --logdir "{tensorboard_dir}"` to inspect the training curves.' "\nDownload the archive below to explore the run offline." )
if missing_paths: skipped = ", ".join(missing_paths) status = f"⚠️ Skipped missing files: {skipped}\n" + status
artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir), result["model_path"] )
return ( status, report_df, result["history"], confusion_df, download_button_state(result["model_path"]), download_button_state(result["scaler_path"]), download_button_state(result["metadata_path"]), download_button_state(tensorboard_zip), gr.update(value=result.get("label_column", label_column)), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), ) except Exception as exc: artifact_choices, selected_artifact = gather_artifact_choices( str(base_dir) ) return ( f"Training failed: {exc}", pd.DataFrame(), {}, pd.DataFrame(), download_button_state(None), download_button_state(None), download_button_state(None), download_button_state(None), gr.update(), gr.update( choices=artifact_choices, value=selected_artifact ), download_button_state(selected_artifact), )
def _check_progress(output_dir, model_filename, current_messages): """Check training progress by reading status file and accumulate messages.""" model_path = resolve_output_path( output_dir, model_filename, Path(LOCAL_MODEL_FILE).name ) status_file = model_path.parent / "training_status.txt" status_message = read_training_status(str(status_file))
# Add timestamp to the message from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S") new_message = f"[{timestamp}] {status_message}"
# Accumulate messages, keeping last 50 lines to prevent overflow if current_messages: lines = current_messages.split("\n") lines.append(new_message) # Keep only last 50 lines if len(lines) > 50: lines = lines[-50:] accumulated_messages = "\n".join(lines) else: accumulated_messages = new_message
return accumulated_messages
train_button.click( _run_training, inputs=[ training_files_state, label_input, model_selector, sequence_length_train, stride_train, validation_train, batch_train, epochs_train, output_directory, model_name, scaler_name, metadata_name, tensorboard_toggle, ], outputs=[ training_status, report_output, history_output, confusion_output, model_download_button, scaler_download_button, metadata_download_button, tensorboard_download_button, label_input, artifact_browser, artifact_download_button, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
progress_button.click( _check_progress, inputs=[output_directory, model_name, progress_messages], outputs=[progress_messages], )
year_selector.change( on_year_change, inputs=[year_selector], outputs=[ month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_selector.change( on_month_change, inputs=[year_selector, month_selector], outputs=[day_selector, available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_selector.change( on_day_change, inputs=[year_selector, month_selector, day_selector], outputs=[available_files, repo_status], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
download_button.click( download_selected_files, inputs=[ year_selector, month_selector, day_selector, available_files, label_input, ], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
year_download_button.click( download_year_bundle, inputs=[year_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
month_download_button.click( download_month_bundle, inputs=[year_selector, month_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
day_download_button.click( download_day_bundle, inputs=[year_selector, month_selector, day_selector, label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _reload_dataset(current_label): local = load_repository_training_files( current_label, force_refresh=True ) remote = refresh_remote_browser(force_refresh=True) return (*local, *remote)
dataset_refresh.click( _reload_dataset, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
clear_cache_button.click( clear_downloaded_cache, inputs=[label_input], outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], concurrency_limit=EVENT_CONCURRENCY_LIMIT, )
def _initialise_dataset(): local = load_repository_training_files( LABEL_COLUMN, force_refresh=False ) remote = refresh_remote_browser(force_refresh=False) return (*local, *remote)
demo.load( _initialise_dataset, inputs=None, outputs=[ training_files_state, training_files_summary, label_input, dataset_info, year_selector, month_selector, day_selector, available_files, repo_status, ], queue=False, )
return demo
# --------------------------------------------------------------------------------------# Launch helpers# --------------------------------------------------------------------------------------
def resolve_server_port() -> int: for env_var in ("PORT", "GRADIO_SERVER_PORT"): value = os.environ.get(env_var) if value: try: return int(value) except ValueError: print(f"Ignoring invalid port value from {env_var}: {value}") return 7860
def main(): print("Building Gradio interface...") try: demo = build_interface() print("Interface built successfully") except Exception as e: print(f"Failed to build interface: {e}") import traceback
traceback.print_exc() return
print("Setting up queue...") try: demo.queue(max_size=QUEUE_MAX_SIZE) print("Queue configured") except Exception as e: print(f"Failed to configure queue: {e}")
try: port = resolve_server_port() print(f"Launching Gradio app on port {port}") demo.launch(server_name="0.0.0.0", server_port=port, show_error=True) except OSError as exc: print("Failed to launch on requested port:", exc) try: demo.launch(server_name="0.0.0.0", show_error=True) except Exception as e: print(f"Failed to launch completely: {e}") except Exception as e: print(f"Unexpected launch error: {e}") import traceback
traceback.print_exc()
if __name__ == "__main__": print("=" * 50) print("PMU Fault Classification App Starting") print(f"Python version: {os.sys.version}") print(f"Working directory: {os.getcwd()}") print(f"HUB_REPO: {HUB_REPO}") print(f"Model available: {MODEL is not None}") print(f"Scaler available: {SCALER is not None}") print("=" * 50) main()5 unmodified lines6789101149 unmodified lines6162636465669 unmodified lines7677787980818247 unmodified lines13013113213313413513613713813914014114214312 unmodified lines15615715815916016117 unmodified lines1791801811821831845 unmodified lines1901911921931941951961971981998 unmodified lines2082092102112122136 unmodified lines22022122222322422522622722822931 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852864 unmodified lines29129229329429529666 unmodified lines3633643653663673683697 unmodified lines37737837938038138238313 unmodified lines3973983994004014024031 unmodified line40540640740840941041139 unmodified lines45145245345445545645730 unmodified lines48848949049149249349450 unmodified lines54554654754854955055155255355455524 unmodified lines580581582583584585586587588146 unmodified lines73573673773873974074198 unmodified lines84084184284384484584684784861 unmodified lines910911912913914915916917918136 unmodified lines10551056105710581059106067 unmodified lines11281129113011311132113311349 unmodified lines114411451146114711481149115011511152115311541155115641 unmodified lines11981199120012011202120312046 unmodified lines12111212121312141215121627 unmodified lines12441245124612471248124912507 unmodified lines12581259126012611262126312641265126612679 unmodified lines12771278127912801281128212836 unmodified lines129012911292129312941295129612971298129913001301130260 unmodified lines13631364136513661367136813691370137113721373137413751 unmodified line13771378137913801381138213833 unmodified lines138713881389139013911392139313 unmodified lines140714081409141014111412141327 unmodified lines14411442144314441445144614476 unmodified lines1454145514561457145814591460146115 unmodified lines147714781479148014811482148369 unmodified lines1553155415551556155715581559185 unmodified lines174517461747174817491750175159 unmodified lines18111812181318141815181618171818181918201821182218233 unmodified lines18271828182918301831183218331834183518361837183839 unmodified lines18781879188018811882188318842 unmodified lines188718881889189018911892189318941895189618975 unmodified lines19031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192618 unmodified lines1945194619471948194919501951195213 unmodified lines196619671968196919701971197215 unmodified lines198819891990199119921993199410 unmodified lines20052006200720082009201020117 unmodified lines2019202020212022202320242025202620272028202920302031203220332034203541 unmodified lines207720782079208020812082208374 unmodified lines215821592160216121622163216432 unmodified lines219721982199220022012202220321 unmodified lines22252226222722282229223013 unmodified lines22442245224622472248224917 unmodified lines22672268226922702271227222732274227522762277227822792280228122825 unmodified linesraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""from __future__ import annotationsimport json49 unmodified lines# Utility functions for loading artifacts# --------------------------------------------------------------------------------------def download_from_hub(filename: str) -> Optional[Path]:if not HUB_REPO or not filename:return None9 unmodified linesreturn Nonedef resolve_artifact(local_name: str, env_var: str, hub_filename: str) -> Optional[Path]:print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}")candidates = [Path(local_name)] if local_name else []if local_name:47 unmodified linesMODEL_PATH = Nonetry:SCALER_PATH = resolve_artifact(LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME)print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e:print(f"Scaler path resolution failed: {e}")SCALER_PATH = Nonetry:METADATA_PATH = resolve_artifact(LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME)print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e:print(f"Metadata path resolution failed: {e}")12 unmodified lines# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2def try_load_model(path: Optional[Path], model_type: str, model_format: str):if not path:return None17 unmodified linesMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"def _model_output_path(filename: str) -> str:return str(MODEL_OUTPUT_DIR / Path(filename).name)5 unmodified lines}REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path(os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)TRAINING_DATA_REPO = os.environ.get("PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)8 unmodified linesflex-direction: column;gap: 0.75rem;border-radius: 0.75rem;}#available-files-grid {6 unmodified linesmin-height: 16rem;}#available-files-section:has(.gradio-loading) {isolation: isolate;}#available-files-grid .wrap {display: grid;grid-template-columns: repeat(4, minmax(0, 1fr));31 unmodified lineswhite-space: nowrap;}#available-files-grid .gradio-loading {position: absolute;inset: 0;width: auto;height: auto;min-height: 100%;display: flex;align-items: center;justify-content: center;background: rgba(10, 14, 23, 0.72);border-radius: 0.75rem;z-index: 10;padding: 1.5rem;pointer-events: auto;}#available-files-grid .gradio-loading > * {width: 100%;}#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,4 unmodified linesmax-width: none !important;}#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label {66 unmodified linesreturn f"{base}?ref={TRAINING_DATA_BRANCH}"def list_remote_directory(path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]:key = _github_cache_key(path)if not force_refresh and key in GITHUB_CONTENT_CACHE:return GITHUB_CONTENT_CACHE[key]7 unmodified linespayload = response.json()if not isinstance(payload, list):raise RuntimeError("Unexpected GitHub API payload. Expected a directory listing.")GITHUB_CONTENT_CACHE[key] = payloadreturn payload13 unmodified linesreturn sorted(months)def list_remote_days(year: str, month: str, *, force_refresh: bool = False) -> List[str]:if not year or not month:return []entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh)1 unmodified linereturn sorted(days)def list_remote_files(year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]:if not year or not month or not day:return []entries = list_remote_directory(39 unmodified linesreturn str(name).strip().lower()def guess_label_from_columns(columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]:if not columns:return preferred30 unmodified lines"""Read the current training status from file."""try:if Path(status_file_path).exists():with open(status_file_path, 'r') as f:return f.read().strip()except Exception:pass50 unmodified linessummary = summarise_training_files(valid_paths, notes)preferred = current_label or LABEL_COLUMNdropdown_choices = sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN]guessed = guess_label_from_columns(dropdown_choices, preferred)dropdown_value = guessed or preferred or LABEL_COLUMNreturn valid_paths, summary, gr.update(choices=dropdown_choices, value=dropdown_value)def append_training_files(new_files, existing_paths: Sequence[str], current_label: str):24 unmodified linesbreakcsv_paths = sorted(str(path)for path in TRAINING_DATA_DIR.rglob("*.csv")if path.is_file())if not csv_paths:message = (146 unmodified linesnotes: List[str] = []for filename in filenames:try:path = download_repository_file(year or "", month or "", day or "", filename)success.append(str(path))except Exception as exc:notes.append(f"⚠️ {filename}: {exc}")98 unmodified linesdownload_repository_file(year, month, day, filename)downloaded += 1except Exception as exc:notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")local = load_repository_training_files(current_label)message_lines = []61 unmodified linesdownload_repository_file(year, month, day, filename)downloaded += 1except Exception as exc:notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")local = load_repository_training_files(current_label)message_lines = []136 unmodified linesgr.update(value=None),)PROJECT_OVERVIEW_MD = """## Project Overview67 unmodified linesdf = Nonefor separator in ("\t", ",", ";"):try:df = pd.read_csv(path, sep=separator, engine="python", encoding="utf-8-sig")breakexcept Exception:df = None9 unmodified lines# Check if we have enough data for trainingif len(df) < 100:print(f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training.")# Check for label columnhas_label = any(col.lower() in ['fault', 'label', 'class', 'target'] for col in df.columns)if not has_label:print("Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples.")df['Fault'] = 'Normal' # Add dummy label for training# Create column mapping - map similar column names to expected formatcolumn_mapping = {}41 unmodified linesdef apply_metadata(metadata: Dict[str, Any]) -> None:global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMATFEATURE_COLUMNS = [str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS)]LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])]LABEL_COLUMN = str(metadata.get("label_column", "Fault"))SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH))6 unmodified linesapply_metadata(METADATA)def sync_label_classes_from_model(model: Optional[object]) -> None:global LABEL_CLASSESif model is None:27 unmodified linesprint(f"Label sync failed: {e}")print("Application initialization completed.")print(f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None:7 unmodified linesSCALER = try_load_scaler(scaler_path)sync_label_classes_from_model(MODEL)# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------def ensure_ready():if MODEL is None or SCALER is None:raise RuntimeError(9 unmodified linescleaned = re.sub(r"[;\n\t]+", ",", text.strip())arr = np.fromstring(cleaned, sep=",")if arr.size == 0:raise ValueError("No feature values were parsed. Please enter comma-separated numbers.")return arr.astype(np.float32)6 unmodified linesreturn scaled.reshape(shape)def make_sliding_windows(data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray:if data.shape[0] < sequence_length:raise ValueError(f"The dataset contains {data.shape[0]} rows which is less than the requested sequence "f"length {sequence_length}. Provide more samples or reduce the sequence length.")windows = [data[start : start + sequence_length] for start in range(0, data.shape[0] - sequence_length + 1, stride)]return np.stack(windows)60 unmodified linespayload.append({"window": int(idx),"probabilities": {label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0])},})return payloaddef predict_sequences(sequences: np.ndarray) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]:ensure_ready()sequences = apply_scaler(sequences.astype(np.float32))if MODEL_TYPE == "svm":1 unmodified lineif hasattr(MODEL, "predict_proba"):probs = MODEL.predict_proba(flattened)else:raise RuntimeError("Loaded SVM model does not expose predict_proba. Retrain with probability=True.")else:probs = MODEL.predict(sequences, verbose=0)table = format_predictions(probs)3 unmodified linesreturn status, table, json_probsdef predict_from_text(text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]:arr = parse_text_features(text)n_features = len(FEATURE_COLUMNS)if arr.size % n_features != 0:13 unmodified linesreturn status, table, probsdef predict_from_csv(file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]:df = load_measurement_csv(file_obj.name)sequences = dataframe_to_sequences(df,27 unmodified linesreturn pd.DataFrame(rows)def confusion_matrix_to_dataframe(confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame:if not confusion:return pd.DataFrame()df = pd.DataFrame(confusion, index=list(labels), columns=list(labels))6 unmodified lines# Gradio interface# --------------------------------------------------------------------------------------def build_interface() -> gr.Blocks:theme = gr.themes.Soft(primary_hue="sky", secondary_hue="blue", neutral_hue="gray").set(body_background_fill="#1f1f1f",body_text_color="#f5f5f5",block_background_fill="#262626",15 unmodified linesexcept Exception:return str(path)with gr.Blocks(title="Fault Classification - PMU Data", theme=theme, css=APP_CSS) as demo:gr.Markdown("# Fault Classification for PMU & PV Data")gr.Markdown("🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers."69 unmodified linesreturn predict_from_csv(file_obj, sequence_length, stride)if text and text.strip():return predict_from_text(text, sequence_length)return "Please upload a CSV file or provide feature values.", pd.DataFrame(), []except Exception as exc:return f"Prediction failed: {exc}", pd.DataFrame(), []185 unmodified linesoutput_directory.change(on_output_directory_change,inputs=[output_directory, artifact_browser],outputs=[output_directory, artifact_browser, artifact_download_button],concurrency_limit=EVENT_CONCURRENCY_LIMIT,)59 unmodified lineswith gr.Row():train_button = gr.Button("🛠️ Start Training", variant="primary")progress_button = gr.Button("📊 Check Progress", variant="secondary")# Training status displaytraining_status = gr.Textbox(label="Training Status", interactive=False)report_output = gr.Dataframe(label="Classification report", interactive=False)history_output = gr.JSON(label="Training history")confusion_output = gr.Dataframe(label="Confusion matrix", interactive=False)# Message area at the bottom for progress updateswith gr.Accordion("📋 Progress Messages", open=True):3 unmodified linesmax_lines=20,interactive=False,autoscroll=True,placeholder="Click 'Check Progress' to see training updates...")with gr.Row():gr.Button("🗑️ Clear Messages", variant="secondary").click(lambda: "",outputs=[progress_messages])def _run_training(39 unmodified linesstatus_file = model_path.parent / "training_status.txt"# Initialize statuswith open(status_file, 'w') as f:f.write("Starting training setup...")if not file_paths:2 unmodified lines"Use 'Reload dataset from database' and try again.")with open(status_file, 'w') as f:f.write("Loading and validating CSV files...")available_paths = [path for path in file_paths if Path(path).exists()]missing_paths = [Path(path).name for path in file_paths if not Path(path).exists()]if not available_paths:raise ValueError("Database training dataset is unavailable. Reload the dataset and retry."5 unmodified lines# Validate data size and provide recommendationstotal_samples = len(combined)if total_samples < 100:print(f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results.")print("Automatically switching to SVM for small dataset compatibility.")if model_choice in ["cnn_lstm", "tcn"]:model_choice = "svm"print(f"Model type changed to SVM for better small dataset performance.")if total_samples < 10:raise ValueError(f"Insufficient data: {total_samples} samples. Need at least 10 samples for training.")label_column = (label_column or LABEL_COLUMN).strip()if not label_column:raise ValueError("Label column name cannot be empty.")model_choice = (model_choice or "CNN-LSTM").lower().replace("-", "_")if model_choice not in {"cnn_lstm", "tcn", "svm"}:raise ValueError("Select CNN-LSTM, TCN, or SVM for the model architecture.")with open(status_file, 'w') as f:f.write(f"Starting {model_choice.upper()} training with {len(combined)} samples...")# Start trainingresult = train_from_dataframe(18 unmodified linesPath(result["metadata_path"]),)report_df = classification_report_to_dataframe(result["classification_report"])confusion_df = confusion_matrix_to_dataframe(result["confusion_matrix"], result["class_names"])tensorboard_dir = result.get("tensorboard_log_dir")tensorboard_zip = result.get("tensorboard_zip_path")13 unmodified linesif tensorboard_dir:status += (f"\nTensorBoard logs directory: {tensorboard_dir}"f"\nRun `tensorboard --logdir \"{tensorboard_dir}\"` to inspect the training curves.""\nDownload the archive below to explore the run offline.")15 unmodified linesdownload_button_state(result["metadata_path"]),download_button_state(tensorboard_zip),gr.update(value=result.get("label_column", label_column)),gr.update(choices=artifact_choices, value=selected_artifact),download_button_state(selected_artifact),)except Exception as exc:10 unmodified linesdownload_button_state(None),download_button_state(None),gr.update(),gr.update(choices=artifact_choices, value=selected_artifact),download_button_state(selected_artifact),)7 unmodified lines# Add timestamp to the messagefrom datetime import datetimetimestamp = datetime.now().strftime("%H:%M:%S")new_message = f"[{timestamp}] {status_message}"# Accumulate messages, keeping last 50 lines to prevent overflowif current_messages:lines = current_messages.split('\n')lines.append(new_message)# Keep only last 50 linesif len(lines) > 50:lines = lines[-50:]accumulated_messages = '\n'.join(lines)else:accumulated_messages = new_message41 unmodified linesyear_selector.change(on_year_change,inputs=[year_selector],outputs=[month_selector, day_selector, available_files, repo_status],concurrency_limit=EVENT_CONCURRENCY_LIMIT,)74 unmodified lines)def _reload_dataset(current_label):local = load_repository_training_files(current_label, force_refresh=True)remote = refresh_remote_browser(force_refresh=True)return (*local, *remote)32 unmodified lines)def _initialise_dataset():local = load_repository_training_files(LABEL_COLUMN, force_refresh=False)remote = refresh_remote_browser(force_refresh=False)return (*local, *remote)21 unmodified lines# Launch helpers# --------------------------------------------------------------------------------------def resolve_server_port() -> int:for env_var in ("PORT", "GRADIO_SERVER_PORT"):value = os.environ.get(env_var)13 unmodified linesexcept Exception as e:print(f"Failed to build interface: {e}")import tracebacktraceback.print_exc()return17 unmodified linesexcept Exception as e:print(f"Unexpected launch error: {e}")import tracebacktraceback.print_exc()if __name__ == "__main__":print("="*50)print("PMU Fault Classification App Starting")print(f"Python version: {os.sys.version}")print(f"Working directory: {os.getcwd()}")print(f"HUB_REPO: {HUB_REPO}")print(f"Model available: {MODEL is not None}")print(f"Scaler available: {SCALER is not None}")print("="*50)main()5 unmodified lines678910111249 unmodified lines626364656667689 unmodified lines78798081828384858647 unmodified lines13413513613713813914014114214314414514614714814915015112 unmodified lines16416516616716816917017 unmodified lines1881891901911921931945 unmodified lines2002012022032042052062072082092102112122138 unmodified lines2222232242252262272286 unmodified lines23523623723823924031 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253264 unmodified lines33133233333433533633733833966 unmodified lines4064074084094104114124134147 unmodified lines42242342442542642742842943013 unmodified lines4444454464474484494504514521 unmodified line45445545645745845946046146239 unmodified lines50250350450550650750850951030 unmodified lines54154254354454554654750 unmodified lines59859960060160260360460560660760860961061161261361424 unmodified lines639640641642643644645146 unmodified lines79279379479579679779879980098 unmodified lines89990090190290390490561 unmodified lines967968969970971972973136 unmodified lines111011111112111311141115111667 unmodified lines1184118511861187118811891190119111929 unmodified lines120212031204120512061207120812091210121112121213121412151216121712181219122041 unmodified lines1262126312641265126612671268126912706 unmodified lines127712781279128012811282128327 unmodified lines1311131213131314131513161317131813197 unmodified lines1327132813291330133113321333133413351336133713389 unmodified lines1348134913501351135213531354135513566 unmodified lines13631364136513661367136813691370137113721373137413751376137713781379138060 unmodified lines144114421443144414451446144714481449145014511452145314541455145614571 unmodified line1459146014611462146314641465146614673 unmodified lines14711472147314741475147614771478147913 unmodified lines14931494149514961497149814991500150127 unmodified lines1529153015311532153315341535153615376 unmodified lines1544154515461547154815491550155115521553155415 unmodified lines15701571157215731574157515761577157869 unmodified lines16481649165016511652165316541655165616571658185 unmodified lines1844184518461847184818491850185118521853185459 unmodified lines19141915191619171918191919201921192219231924192519261927192819291930193119323 unmodified lines1936193719381939194019411942194319441945194639 unmodified lines19861987198819891990199119922 unmodified lines199519961997199819992000200120022003200420052006200720082009201020115 unmodified lines2017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205418 unmodified lines20732074207520762077207820792080208120822083208413 unmodified lines209820992100210121022103210415 unmodified lines21202121212221232124212521262127212810 unmodified lines2139214021412142214321442145214621477 unmodified lines21552156215721582159216021612162216321642165216621672168216921702171217241 unmodified lines22142215221622172218221922202221222222232224222574 unmodified lines23002301230223032304230523062307230832 unmodified lines23412342234323442345234623472348234921 unmodified lines237123722373237423752376237713 unmodified lines239123922393239423952396239717 unmodified lines241524162417241824192420242124222423242424252426242724282429243024315 unmodified linesraw PMU time-series CSV uploads as well as manual comma separated featurevectors."""from __future__ import annotationsimport json49 unmodified lines# Utility functions for loading artifacts# --------------------------------------------------------------------------------------def download_from_hub(filename: str) -> Optional[Path]:if not HUB_REPO or not filename:return None9 unmodified linesreturn Nonedef resolve_artifact(local_name: str, env_var: str, hub_filename: str) -> Optional[Path]:print(f"Resolving artifact: {local_name}, env: {env_var}, hub: {hub_filename}")candidates = [Path(local_name)] if local_name else []if local_name:47 unmodified linesMODEL_PATH = Nonetry:SCALER_PATH = resolve_artifact(LOCAL_SCALER_FILE, ENV_SCALER_PATH, HUB_SCALER_FILENAME)print(f"Scaler path resolved: {SCALER_PATH}")except Exception as e:print(f"Scaler path resolution failed: {e}")SCALER_PATH = Nonetry:METADATA_PATH = resolve_artifact(LOCAL_METADATA_FILE, ENV_METADATA_PATH, HUB_METADATA_FILENAME)print(f"Metadata path resolved: {METADATA_PATH}")except Exception as e:print(f"Metadata path resolution failed: {e}")12 unmodified lines# ``concurrency_count`` parameter when enabling Gradio's request queue.EVENT_CONCURRENCY_LIMIT = 2def try_load_model(path: Optional[Path], model_type: str, model_format: str):if not path:return None17 unmodified linesMODEL_TYPE: str = "cnn_lstm"MODEL_FORMAT: str = "keras"def _model_output_path(filename: str) -> str:return str(MODEL_OUTPUT_DIR / Path(filename).name)5 unmodified lines}REQUIRED_PMU_COLUMNS: Tuple[str, ...] = tuple(DEFAULT_FEATURE_COLUMNS)TRAINING_UPLOAD_DIR = Path(os.environ.get("PMU_TRAINING_UPLOAD_DIR", "training_uploads"))TRAINING_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)TRAINING_DATA_REPO = os.environ.get("PMU_TRAINING_DATA_REPO", "VincentCroft/ThesisModelData")TRAINING_DATA_BRANCH = os.environ.get("PMU_TRAINING_DATA_BRANCH", "main")TRAINING_DATA_DIR = Path(os.environ.get("PMU_TRAINING_DATA_DIR", "training_dataset"))TRAINING_DATA_DIR.mkdir(parents=True, exist_ok=True)8 unmodified linesflex-direction: column;gap: 0.75rem;border-radius: 0.75rem;isolation: isolate;}#available-files-grid {6 unmodified linesmin-height: 16rem;}#available-files-grid .wrap {display: grid;grid-template-columns: repeat(4, minmax(0, 1fr));31 unmodified lineswhite-space: nowrap;}#available-files-section .gradio-loading,#available-files-grid .gradio-loading {position: absolute;top: 0;left: 0;right: 0;bottom: 0;width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;background: rgba(10, 14, 23, 0.92);border-radius: 0.75rem;z-index: 999;padding: 1.5rem;pointer-events: auto;}#available-files-section .gradio-loading,#available-files-grid .gradio-loading {position: absolute;top: 0;left: 0;right: 0;bottom: 0;width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;background: rgba(10, 14, 23, 0.92);border-radius: 0.75rem;z-index: 999;padding: 1.5rem;pointer-events: auto;}#available-files-section .gradio-loading > *,#available-files-grid .gradio-loading > * {width: 100%;}#available-files-section .gradio-loading progress,#available-files-section .gradio-loading .progress-bar,#available-files-section .gradio-loading .loading-progress,#available-files-section .gradio-loading [role="progressbar"],#available-files-section .gradio-loading .wrap,#available-files-section .gradio-loading .inner,#available-files-grid .gradio-loading progress,#available-files-grid .gradio-loading .progress-bar,#available-files-grid .gradio-loading .loading-progress,4 unmodified linesmax-width: none !important;}#available-files-section .gradio-loading .status,#available-files-section .gradio-loading .message,#available-files-section .gradio-loading .label,#available-files-grid .gradio-loading .status,#available-files-grid .gradio-loading .message,#available-files-grid .gradio-loading .label {66 unmodified linesreturn f"{base}?ref={TRAINING_DATA_BRANCH}"def list_remote_directory(path: str = "", *, force_refresh: bool = False) -> List[Dict[str, Any]]:key = _github_cache_key(path)if not force_refresh and key in GITHUB_CONTENT_CACHE:return GITHUB_CONTENT_CACHE[key]7 unmodified linespayload = response.json()if not isinstance(payload, list):raise RuntimeError("Unexpected GitHub API payload. Expected a directory listing.")GITHUB_CONTENT_CACHE[key] = payloadreturn payload13 unmodified linesreturn sorted(months)def list_remote_days(year: str, month: str, *, force_refresh: bool = False) -> List[str]:if not year or not month:return []entries = list_remote_directory(f"{year}/{month}", force_refresh=force_refresh)1 unmodified linereturn sorted(days)def list_remote_files(year: str, month: str, day: str, *, force_refresh: bool = False) -> List[str]:if not year or not month or not day:return []entries = list_remote_directory(39 unmodified linesreturn str(name).strip().lower()def guess_label_from_columns(columns: Sequence[str], preferred: Optional[str] = None) -> Optional[str]:if not columns:return preferred30 unmodified lines"""Read the current training status from file."""try:if Path(status_file_path).exists():with open(status_file_path, "r") as f:return f.read().strip()except Exception:pass50 unmodified linessummary = summarise_training_files(valid_paths, notes)preferred = current_label or LABEL_COLUMNdropdown_choices = (sorted(columns_map.values()) if columns_map else [preferred or LABEL_COLUMN])guessed = guess_label_from_columns(dropdown_choices, preferred)dropdown_value = guessed or preferred or LABEL_COLUMNreturn (valid_paths,summary,gr.update(choices=dropdown_choices, value=dropdown_value),)def append_training_files(new_files, existing_paths: Sequence[str], current_label: str):24 unmodified linesbreakcsv_paths = sorted(str(path) for path in TRAINING_DATA_DIR.rglob("*.csv") if path.is_file())if not csv_paths:message = (146 unmodified linesnotes: List[str] = []for filename in filenames:try:path = download_repository_file(year or "", month or "", day or "", filename)success.append(str(path))except Exception as exc:notes.append(f"⚠️ {filename}: {exc}")98 unmodified linesdownload_repository_file(year, month, day, filename)downloaded += 1except Exception as exc:notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")local = load_repository_training_files(current_label)message_lines = []61 unmodified linesdownload_repository_file(year, month, day, filename)downloaded += 1except Exception as exc:notes.append(f"⚠️ {year}/{month}/{day}/{filename}: {exc}")local = load_repository_training_files(current_label)message_lines = []136 unmodified linesgr.update(value=None),)PROJECT_OVERVIEW_MD = """## Project Overview67 unmodified linesdf = Nonefor separator in ("\t", ",", ";"):try:df = pd.read_csv(path, sep=separator, engine="python", encoding="utf-8-sig")breakexcept Exception:df = None9 unmodified lines# Check if we have enough data for trainingif len(df) < 100:print(f"Warning: Only {len(df)} rows of data. Recommend at least 1000 rows for effective training.")# Check for label columnhas_label = any(col.lower() in ["fault", "label", "class", "target"] for col in df.columns)if not has_label:print("Warning: No label column found. Adding dummy 'Fault' column with value 'Normal' for all samples.")df["Fault"] = "Normal" # Add dummy label for training# Create column mapping - map similar column names to expected formatcolumn_mapping = {}41 unmodified linesdef apply_metadata(metadata: Dict[str, Any]) -> None:global FEATURE_COLUMNS, LABEL_CLASSES, LABEL_COLUMN, SEQUENCE_LENGTH, DEFAULT_WINDOW_STRIDE, MODEL_TYPE, MODEL_FORMATFEATURE_COLUMNS = [str(col) for col in metadata.get("feature_columns", DEFAULT_FEATURE_COLUMNS)]LABEL_CLASSES = [str(label) for label in metadata.get("label_classes", [])]LABEL_COLUMN = str(metadata.get("label_column", "Fault"))SEQUENCE_LENGTH = int(metadata.get("sequence_length", DEFAULT_SEQUENCE_LENGTH))6 unmodified linesapply_metadata(METADATA)def sync_label_classes_from_model(model: Optional[object]) -> None:global LABEL_CLASSESif model is None:27 unmodified linesprint(f"Label sync failed: {e}")print("Application initialization completed.")print(f"Ready to start Gradio interface. Model available: {MODEL is not None}, Scaler available: {SCALER is not None}")def refresh_artifacts(model_path: Path, scaler_path: Path, metadata_path: Path) -> None:7 unmodified linesSCALER = try_load_scaler(scaler_path)sync_label_classes_from_model(MODEL)# --------------------------------------------------------------------------------------# Pre-processing helpers# --------------------------------------------------------------------------------------def ensure_ready():if MODEL is None or SCALER is None:raise RuntimeError(9 unmodified linescleaned = re.sub(r"[;\n\t]+", ",", text.strip())arr = np.fromstring(cleaned, sep=",")if arr.size == 0:raise ValueError("No feature values were parsed. Please enter comma-separated numbers.")return arr.astype(np.float32)6 unmodified linesreturn scaled.reshape(shape)def make_sliding_windows(data: np.ndarray, sequence_length: int, stride: int) -> np.ndarray:if data.shape[0] < sequence_length:raise ValueError(f"The dataset contains {data.shape[0]} rows which is less than the requested sequence "f"length {sequence_length}. Provide more samples or reduce the sequence length.")windows = [data[start : start + sequence_length]for start in range(0, data.shape[0] - sequence_length + 1, stride)]return np.stack(windows)60 unmodified linespayload.append({"window": int(idx),"probabilities": {label_name(i): float(prob_row[i]) for i in range(prob_row.shape[0])},})return payloaddef predict_sequences(sequences: np.ndarray,) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]:ensure_ready()sequences = apply_scaler(sequences.astype(np.float32))if MODEL_TYPE == "svm":1 unmodified lineif hasattr(MODEL, "predict_proba"):probs = MODEL.predict_proba(flattened)else:raise RuntimeError("Loaded SVM model does not expose predict_proba. Retrain with probability=True.")else:probs = MODEL.predict(sequences, verbose=0)table = format_predictions(probs)3 unmodified linesreturn status, table, json_probsdef predict_from_text(text: str, sequence_length: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]:arr = parse_text_features(text)n_features = len(FEATURE_COLUMNS)if arr.size % n_features != 0:13 unmodified linesreturn status, table, probsdef predict_from_csv(file_obj, sequence_length: int, stride: int) -> Tuple[str, pd.DataFrame, List[Dict[str, object]]]:df = load_measurement_csv(file_obj.name)sequences = dataframe_to_sequences(df,27 unmodified linesreturn pd.DataFrame(rows)def confusion_matrix_to_dataframe(confusion: Sequence[Sequence[float]], labels: Sequence[str]) -> pd.DataFrame:if not confusion:return pd.DataFrame()df = pd.DataFrame(confusion, index=list(labels), columns=list(labels))6 unmodified lines# Gradio interface# --------------------------------------------------------------------------------------def build_interface() -> gr.Blocks:theme = gr.themes.Soft(primary_hue="sky", secondary_hue="blue", neutral_hue="gray").set(body_background_fill="#1f1f1f",body_text_color="#f5f5f5",block_background_fill="#262626",15 unmodified linesexcept Exception:return str(path)with gr.Blocks(title="Fault Classification - PMU Data", theme=theme, css=APP_CSS) as demo:gr.Markdown("# Fault Classification for PMU & PV Data")gr.Markdown("🖥️ TensorFlow is locked to CPU execution so the Space can run without CUDA drivers."69 unmodified linesreturn predict_from_csv(file_obj, sequence_length, stride)if text and text.strip():return predict_from_text(text, sequence_length)return ("Please upload a CSV file or provide feature values.",pd.DataFrame(),[],)except Exception as exc:return f"Prediction failed: {exc}", pd.DataFrame(), []185 unmodified linesoutput_directory.change(on_output_directory_change,inputs=[output_directory, artifact_browser],outputs=[output_directory,artifact_browser,artifact_download_button,],concurrency_limit=EVENT_CONCURRENCY_LIMIT,)59 unmodified lineswith gr.Row():train_button = gr.Button("🛠️ Start Training", variant="primary")progress_button = gr.Button("📊 Check Progress", variant="secondary")# Training status displaytraining_status = gr.Textbox(label="Training Status", interactive=False)report_output = gr.Dataframe(label="Classification report", interactive=False)history_output = gr.JSON(label="Training history")confusion_output = gr.Dataframe(label="Confusion matrix", interactive=False)# Message area at the bottom for progress updateswith gr.Accordion("📋 Progress Messages", open=True):3 unmodified linesmax_lines=20,interactive=False,autoscroll=True,placeholder="Click 'Check Progress' to see training updates...",)with gr.Row():gr.Button("🗑️ Clear Messages", variant="secondary").click(lambda: "", outputs=[progress_messages])def _run_training(39 unmodified linesstatus_file = model_path.parent / "training_status.txt"# Initialize statuswith open(status_file, "w") as f:f.write("Starting training setup...")if not file_paths:2 unmodified lines"Use 'Reload dataset from database' and try again.")with open(status_file, "w") as f:f.write("Loading and validating CSV files...")available_paths = [path for path in file_paths if Path(path).exists()]missing_paths = [Path(path).namefor path in file_pathsif not Path(path).exists()]if not available_paths:raise ValueError("Database training dataset is unavailable. Reload the dataset and retry."5 unmodified lines# Validate data size and provide recommendationstotal_samples = len(combined)if total_samples < 100:print(f"Warning: Only {total_samples} samples. Recommend at least 1000 for good results.")print("Automatically switching to SVM for small dataset compatibility.")if model_choice in ["cnn_lstm", "tcn"]:model_choice = "svm"print(f"Model type changed to SVM for better small dataset performance.")if total_samples < 10:raise ValueError(f"Insufficient data: {total_samples} samples. Need at least 10 samples for training.")label_column = (label_column or LABEL_COLUMN).strip()if not label_column:raise ValueError("Label column name cannot be empty.")model_choice = ((model_choice or "CNN-LSTM").lower().replace("-", "_"))if model_choice not in {"cnn_lstm", "tcn", "svm"}:raise ValueError("Select CNN-LSTM, TCN, or SVM for the model architecture.")with open(status_file, "w") as f:f.write(f"Starting {model_choice.upper()} training with {len(combined)} samples...")# Start trainingresult = train_from_dataframe(18 unmodified linesPath(result["metadata_path"]),)report_df = classification_report_to_dataframe(result["classification_report"])confusion_df = confusion_matrix_to_dataframe(result["confusion_matrix"], result["class_names"])tensorboard_dir = result.get("tensorboard_log_dir")tensorboard_zip = result.get("tensorboard_zip_path")13 unmodified linesif tensorboard_dir:status += (f"\nTensorBoard logs directory: {tensorboard_dir}"f'\nRun `tensorboard --logdir "{tensorboard_dir}"` to inspect the training curves.'"\nDownload the archive below to explore the run offline.")15 unmodified linesdownload_button_state(result["metadata_path"]),download_button_state(tensorboard_zip),gr.update(value=result.get("label_column", label_column)),gr.update(choices=artifact_choices, value=selected_artifact),download_button_state(selected_artifact),)except Exception as exc:10 unmodified linesdownload_button_state(None),download_button_state(None),gr.update(),gr.update(choices=artifact_choices, value=selected_artifact),download_button_state(selected_artifact),)7 unmodified lines# Add timestamp to the messagefrom datetime import datetimetimestamp = datetime.now().strftime("%H:%M:%S")new_message = f"[{timestamp}] {status_message}"# Accumulate messages, keeping last 50 lines to prevent overflowif current_messages:lines = current_messages.split("\n")lines.append(new_message)# Keep only last 50 linesif len(lines) > 50:lines = lines[-50:]accumulated_messages = "\n".join(lines)else:accumulated_messages = new_message41 unmodified linesyear_selector.change(on_year_change,inputs=[year_selector],outputs=[month_selector,day_selector,available_files,repo_status,],concurrency_limit=EVENT_CONCURRENCY_LIMIT,)74 unmodified lines)def _reload_dataset(current_label):local = load_repository_training_files(current_label, force_refresh=True)remote = refresh_remote_browser(force_refresh=True)return (*local, *remote)32 unmodified lines)def _initialise_dataset():local = load_repository_training_files(LABEL_COLUMN, force_refresh=False)remote = refresh_remote_browser(force_refresh=False)return (*local, *remote)21 unmodified lines# Launch helpers# --------------------------------------------------------------------------------------def resolve_server_port() -> int:for env_var in ("PORT", "GRADIO_SERVER_PORT"):value = os.environ.get(env_var)13 unmodified linesexcept Exception as e:print(f"Failed to build interface: {e}")import tracebacktraceback.print_exc()return17 unmodified linesexcept Exception as e:print(f"Unexpected launch error: {e}")import tracebacktraceback.print_exc()if __name__ == "__main__":print("=" * 50)print("PMU Fault Classification App Starting")print(f"Python version: {os.sys.version}")print(f"Working directory: {os.getcwd()}")print(f"HUB_REPO: {HUB_REPO}")print(f"Model available: {MODEL is not None}")print(f"Scaler available: {SCALER is not None}")print("=" * 50)main()
.history/app_20251009231256.pyAdded+2282
.history/app_20251009231310.pyAdded+2402
.history/app_20251009232235.pyAdded+2402
.history/app_20251009232247.pyAdded+2431
.history/app_20251009232414.pyAdded+2431
app.py+232-83