Instructions to use haresh2792005/MFAF-Net with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MediaPipe
How to use haresh2792005/MFAF-Net with MediaPipe:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
File size: 6,517 Bytes
c4a514c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | import os
import uuid
from flask import Flask, request, jsonify, render_template, send_from_directory
from mfaf_net.module1_feature_extraction import extract_features
from mfaf_net.module2_patient_analysis import analyze_patient
from mfaf_net.module3_feature_fusion import fuse_features
from mfaf_net.module4_simulation import simulate_procedure
from mfaf_net.module5_comparison import compare_results
from mfaf_net.dataset_loader import get_dataset_stats
from mfaf_net.model_comparison import get_comparison_dict
app = Flask(__name__, template_folder='templates', static_folder='static')
UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'static', 'results')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
SUPPORTED_PROCEDURES = {
'rhinoplasty': 'Rhinoplasty (Nose Reshaping)',
'blepharoplasty': 'Blepharoplasty (Eyelid Surgery)',
'rhytidectomy': 'Rhytidectomy (Face Lift)',
'genioplasty': 'Genioplasty (Chin Surgery)',
'forehead_surgery': 'Forehead Surgery',
'brow_lift': 'Brow Lift',
}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/procedures', methods=['GET'])
def get_procedures():
procedures = [
{'id': k, 'name': v} for k, v in SUPPORTED_PROCEDURES.items()
]
return jsonify({'procedures': procedures})
@app.route('/api/analyze', methods=['POST'])
def analyze():
try:
# --- Validate inputs ---
if 'image' not in request.files:
return jsonify({'error': 'No image file provided'}), 400
image_file = request.files['image']
if image_file.filename == '':
return jsonify({'error': 'Empty filename'}), 400
age = request.form.get('age', '30')
sex = request.form.get('sex', 'Other')
skin_type = request.form.get('skin_type', 'III')
procedure = request.form.get('procedure', 'rhinoplasty')
treatment_history = request.form.get('treatment_history', '0')
if procedure not in SUPPORTED_PROCEDURES:
return jsonify({'error': f'Unsupported procedure: {procedure}'}), 400
# --- Save uploaded image ---
uid = uuid.uuid4().hex
ext = os.path.splitext(image_file.filename)[1] or '.jpg'
original_filename = f'original_{uid}{ext}'
original_path = os.path.join(UPLOAD_FOLDER, original_filename)
image_file.save(original_path)
# --- Module 1: Feature Extraction ---
m1 = extract_features(original_path, UPLOAD_FOLDER, uid)
landmarks_array = m1['landmarks_array']
measurements = m1['measurements']
regions = m1['regions']
annotated_image_path = m1['annotated_image_path']
# --- Module 2: Patient Analysis ---
m2 = analyze_patient(
age=age,
sex=sex,
skin_type=skin_type,
procedure=procedure,
treatment_history=treatment_history,
)
patient_features = m2['feature_vector']
patient_summary = m2['summary']
# --- Module 3: Feature Fusion ---
m3 = fuse_features(
landmarks_array=landmarks_array,
measurements=measurements,
patient_features=patient_features,
procedure=procedure,
)
fused_vector = m3['fused_vector']
attention_weights = m3['attention_weights']
# --- Module 4: Simulation ---
m4 = simulate_procedure(
original_path=original_path,
landmarks_array=landmarks_array,
regions=regions,
procedure=procedure,
output_dir=UPLOAD_FOLDER,
uid=uid,
patient_features=patient_features,
attention_weights=attention_weights,
measurements=measurements,
)
simulated_path = m4['simulated_image_path']
simulation_mode = m4.get('simulation_mode', 'rule_based_geometric')
# --- Module 5: Comparison ---
m5 = compare_results(
original_path=original_path,
simulated_path=simulated_path,
output_dir=UPLOAD_FOLDER,
uid=uid,
)
def to_static(abs_path):
"""Convert absolute path to a URL-friendly static path."""
if abs_path is None:
return None
rel = os.path.relpath(abs_path, os.path.dirname(__file__))
return '/' + rel.replace(os.sep, '/')
return jsonify({
'status': 'success',
'simulation_mode': simulation_mode,
'procedure': procedure,
'procedure_name': SUPPORTED_PROCEDURES[procedure],
'patient_summary': patient_summary,
'attention_weights': attention_weights,
'measurements': {k: float(v) for k, v in measurements.items()},
'original_img': to_static(original_path),
'annotated_img': to_static(annotated_image_path),
'simulated_img': to_static(simulated_path),
'diff_map': to_static(m5['diff_map_path']),
'metrics_chart': to_static(m5['metrics_chart_path']),
'metrics': m5['metrics'],
})
except Exception as exc:
import traceback
return jsonify({'error': str(exc), 'traceback': traceback.format_exc()}), 500
@app.route('/static/results/<path:filename>')
def serve_result(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
@app.route('/api/dataset-info', methods=['GET'])
def dataset_info():
data_root = os.path.join(os.path.dirname(__file__), 'data')
stats = get_dataset_stats(data_root)
return jsonify(stats)
@app.route('/api/model-comparison', methods=['GET'])
def model_comparison():
return jsonify(get_comparison_dict())
@app.route('/api/model-status', methods=['GET'])
def model_status():
from mfaf_net.model_arch import load_trained_model, DEFAULT_MODELS_DIR
import json
model, meta = load_trained_model()
hist_path = os.path.join(DEFAULT_MODELS_DIR, 'training_history.json')
history_summary = None
if os.path.isfile(hist_path):
try:
with open(hist_path, 'r', encoding='utf-8') as f:
history_summary = json.load(f)
except Exception:
history_summary = None
return jsonify({
'trained_model_loaded': model is not None,
'metadata': meta,
'training_summary': history_summary,
})
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(debug=True, host='0.0.0.0', port=port)
|