facial-plastic-surgery-planner 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. facial_plastic_surgery_planner-0.1.0/LICENSE +21 -0
  2. facial_plastic_surgery_planner-0.1.0/MANIFEST.in +13 -0
  3. facial_plastic_surgery_planner-0.1.0/NOTICE.md +14 -0
  4. facial_plastic_surgery_planner-0.1.0/PKG-INFO +170 -0
  5. facial_plastic_surgery_planner-0.1.0/README.md +123 -0
  6. facial_plastic_surgery_planner-0.1.0/bioinfo/__init__.py +0 -0
  7. facial_plastic_surgery_planner-0.1.0/bioinfo/clinical_coding.py +53 -0
  8. facial_plastic_surgery_planner-0.1.0/bioinfo/enrichment.py +80 -0
  9. facial_plastic_surgery_planner-0.1.0/bioinfo/fetch_data.py +57 -0
  10. facial_plastic_surgery_planner-0.1.0/bioinfo/fhir_export.py +54 -0
  11. facial_plastic_surgery_planner-0.1.0/docs/PYPI_README.md +134 -0
  12. facial_plastic_surgery_planner-0.1.0/face_proportions.py +151 -0
  13. facial_plastic_surgery_planner-0.1.0/face_zones.py +210 -0
  14. facial_plastic_surgery_planner-0.1.0/markings.py +128 -0
  15. facial_plastic_surgery_planner-0.1.0/pyproject.toml +37 -0
  16. facial_plastic_surgery_planner-0.1.0/quality_gate.py +186 -0
  17. facial_plastic_surgery_planner-0.1.0/sam_segment.py +144 -0
  18. facial_plastic_surgery_planner-0.1.0/setup.cfg +4 -0
  19. facial_plastic_surgery_planner-0.1.0/setup.py +39 -0
  20. facial_plastic_surgery_planner-0.1.0/smile_symmetry.py +334 -0
  21. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner/__init__.py +5 -0
  22. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner/api.py +72 -0
  23. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner/cli.py +26 -0
  24. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner.egg-info/PKG-INFO +170 -0
  25. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner.egg-info/SOURCES.txt +32 -0
  26. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner.egg-info/dependency_links.txt +1 -0
  27. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner.egg-info/entry_points.txt +2 -0
  28. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner.egg-info/requires.txt +17 -0
  29. facial_plastic_surgery_planner-0.1.0/src/facial_plastic_surgery_planner.egg-info/top_level.txt +1 -0
  30. facial_plastic_surgery_planner-0.1.0/surgeon_compare.py +147 -0
  31. facial_plastic_surgery_planner-0.1.0/surgical_planner.py +247 -0
  32. facial_plastic_surgery_planner-0.1.0/tests/test_package_api.py +50 -0
  33. facial_plastic_surgery_planner-0.1.0/wound_planner.py +432 -0
  34. facial_plastic_surgery_planner-0.1.0/wound_segment.py +219 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Muhammad Allam Rafi and Cindy Rizky Afrilia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ include LICENSE NOTICE.md setup.py
2
+ include markings.py surgical_planner.py wound_planner.py face_proportions.py
3
+ include smile_symmetry.py face_zones.py quality_gate.py sam_segment.py
4
+ include wound_segment.py surgeon_compare.py
5
+ include bioinfo/*.py
6
+ include docs/PYPI_README.md
7
+ recursive-include tests *.py
8
+ exclude face_landmarker.task
9
+ prune models
10
+ prune test_data
11
+ prune assets
12
+ prune app_output
13
+ prune demo_output
@@ -0,0 +1,14 @@
1
+ # Pemberitahuan pihak ketiga
2
+
3
+ Berkas model dan data berikut tidak ditulis oleh proyek ini. Periksa ketentuan terkini sebelum memakai di luar riset.
4
+
5
+ - **MediaPipe Face Landmarker** (Google): Apache-2.0. Model diunduh oleh `scripts/download_models.py`. `test_data/canonical_face_cm.npy` adalah
6
+ mesh wajah kanonik yang diekstrak dari paket model tersebut, dipakai hanya sebagai fixture uji.
7
+ - **MobileSAM** (Zhang dkk.): Apache-2.0. Konversi ONNX oleh Acly (Hugging Face `Acly/MobileSAM`): MIT. Diunduh oleh `scripts/download_models.py`.
8
+ - **Open Targets Platform**: data asosiasi gen-penyakit (snapshot bertanggal di `bioinfo/data/opentargets_snapshot.json`), CC0. https://platform.opentargets.org
9
+ - **Reactome** (melalui pustaka Enrichr `Reactome_2022`): Reactome dilisensikan CC BY 4.0; mohon atribusi. https://reactome.org dan https://maayanlab.cloud/Enrichr
10
+ - **Human Phenotype Ontology (HPO)**: ID istilah diverifikasi dari API resmi; lihat ketentuan atribusi di https://hpo.jax.org
11
+ - **ICD-10 (WHO)**: kode kategori; konfirmasikan dengan edisi yang dipakai institusi Anda.
12
+ - **FHIR R4B**: model validasi dari paket `fhir.resources`.
13
+
14
+ Foto yang dipakai untuk pengujian selama pengembangan berasal dari Wikimedia Commons (domain publik atau Creative Commons) dan **tidak** disertakan di repositori.
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: facial-plastic-surgery-planner
3
+ Version: 0.1.0
4
+ Summary: Composable facial wound geometry, suture marking and research planning tools
5
+ Author: Muhammad Allam Rafi, Cindy Rizky Afrilia
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sharing-123/facial-plastic-surgery-planner
8
+ Project-URL: Repository, https://github.com/sharing-123/facial-plastic-surgery-planner
9
+ Project-URL: Issues, https://github.com/sharing-123/facial-plastic-surgery-planner/issues
10
+ Project-URL: Research archive, https://doi.org/10.5281/zenodo.24412867
11
+ Project-URL: Registration, https://doi.org/10.17605/OSF.IO/ESW47
12
+ Keywords: facial,geometry,wound,research,suture,bioinformatics
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE.md
21
+ Requires-Dist: numpy>=1.26
22
+ Provides-Extra: vision
23
+ Requires-Dist: opencv-python>=4.9; extra == "vision"
24
+ Requires-Dist: mediapipe>=0.10; extra == "vision"
25
+ Requires-Dist: onnxruntime>=1.17; extra == "vision"
26
+ Requires-Dist: scipy>=1.11; extra == "vision"
27
+ Requires-Dist: matplotlib>=3.8; extra == "vision"
28
+ Provides-Extra: bioinformatics
29
+ Requires-Dist: scipy>=1.11; extra == "bioinformatics"
30
+ Requires-Dist: fhir.resources>=8.0; extra == "bioinformatics"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=8; extra == "dev"
33
+ Requires-Dist: build>=1.2; extra == "dev"
34
+ Requires-Dist: twine>=6; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # Facial Plastic Surgery Planner
38
+
39
+ A Python toolkit for calibrated wound geometry, numbered suture guides and
40
+ reconstructive marking research. Use it from notebooks, web services or other
41
+ Python projects. The default installation needs only NumPy and works offline.
42
+
43
+ This is research software, not a validated medical device. Geometric consistency
44
+ does not establish clinical accuracy or the suitability of a closure technique.
45
+ A photograph cannot establish wound depth, vascularity, contamination or nerve injury.
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ python -m pip install facial-plastic-surgery-planner
51
+ ```
52
+
53
+ Optional image processing and bioinformatics dependencies are separate:
54
+
55
+ ```bash
56
+ python -m pip install "facial-plastic-surgery-planner[vision,bioinformatics]"
57
+ ```
58
+
59
+ Python 3.10 or newer is required. Model weights, photographs, external gene
60
+ libraries and the browser application are not included in the distribution.
61
+
62
+ ## Calibrated measurements
63
+
64
+ ```python
65
+ from facial_plastic_surgery_planner import measure_wound
66
+
67
+ report = measure_wound(
68
+ points_px=[[100, 400], [180, 400]],
69
+ pixels_per_mm=8.0,
70
+ rstl_degrees=90.0,
71
+ region="cheek",
72
+ )
73
+ assert report["length_mm"] == 10.0
74
+ assert report["mean_angle_to_rstl_deg"] == 90.0
75
+ ```
76
+
77
+ Image points use x right and y down. The supplied skin tension line direction
78
+ uses x right and y up, measured in degrees modulo 180. Calibration must be
79
+ measured independently. This API does not infer an absolute scale from an image.
80
+ The returned dictionary includes length, chord, tortuosity, alignment and
81
+ elliptical excision geometry. Invalid or degenerate inputs raise `ValueError`.
82
+
83
+ ## Drawing coordinates for other applications
84
+
85
+ ```python
86
+ import json
87
+ from facial_plastic_surgery_planner import create_markings, to_jsonable
88
+
89
+ marks = create_markings([[0, 0], [28, 0]], spacing_mm=4, bite_mm=3)
90
+ assert len(marks["sutures"]) == 7
91
+ payload = json.dumps(to_jsonable(marks), allow_nan=False)
92
+ ```
93
+
94
+ Marking points are millimetres with y up. Each suture has an index, placement
95
+ order, centre and two bite coordinates. W-plasty and serial Z-plasty candidates
96
+ are returned as arrays. Transform these coordinates into your own canvas or
97
+ image frame before drawing. The default dimensions are configurable research
98
+ parameters, not treatment instructions. Algorithms do not model tissue mechanics.
99
+
100
+ ## Command line
101
+
102
+ Create `wound.json`:
103
+
104
+ ```json
105
+ {"points_px": [[100, 400], [180, 400]], "pixels_per_mm": 8, "rstl_degrees": 90}
106
+ ```
107
+
108
+ ```bash
109
+ facial-planner wound.json --output measurements.json
110
+ ```
111
+
112
+ The CLI reads and writes local JSON only. Missing fields and invalid input
113
+ produce an error message and exit code 2.
114
+
115
+ ## Advanced research modules
116
+
117
+ The original implementations are available under the package namespace:
118
+
119
+ * `markings` provides W-plasty, serial Z-plasty and broken-line geometry.
120
+ * `surgical_planner.plan(report, context)` exposes the existing clinical rule
121
+ engine. Its context codes and narrative output retain the original Indonesian
122
+ schema for compatibility. The stable measurement and drawing APIs above use
123
+ English keys. Do not assume that the rule engine outputs are clinically validated.
124
+ * `wound_planner`, `face_zones`, `quality_gate`, `sam_segment` and `wound_segment`
125
+ provide optional image workflows. Install the `vision` extra and supply model
126
+ paths explicitly. Image workflows require appropriate calibration and quality checks.
127
+ * `bioinfo.enrichment.ora(genes, library, background=...)` accepts a caller-supplied
128
+ mapping of pathway names to gene sets. Install the `bioinformatics` extra.
129
+ `load_library(path)` needs an explicit GMT file because third-party datasets
130
+ are not bundled. Clinical coding snapshots likewise must be supplied separately.
131
+ * `surgeon_compare` provides research agreement metrics.
132
+
133
+ The standalone local application and model download helpers remain in the
134
+ [GitHub repository](https://github.com/sharing-123/facial-plastic-surgery-planner).
135
+
136
+ ## Development and verification
137
+
138
+ ```bash
139
+ python -m pip install build twine
140
+ python -m build
141
+ python -m pip install --force-reinstall dist/facial_plastic_surgery_planner-0.1.0-py3-none-any.whl
142
+ python -m pip install pytest
143
+ python -m pytest tests
144
+ python -m twine check dist/*
145
+ ```
146
+
147
+ Build and install a wheel when developing. The build converts the original
148
+ standalone modules to relative imports and extracts unchanged analytic geometry
149
+ into a lightweight module. Editable installation is not supported by this build.
150
+ The source distribution includes these original modules and the build recipe.
151
+ No image models, photographs, credentials or external datasets are packaged.
152
+
153
+ The package tests cover known analytic lengths, calibration, marking coordinates,
154
+ invalid inputs, JSON conversion and the existing clinical rule regressions.
155
+ They assess implementation behaviour, not agreement with surgeons or patient outcomes.
156
+
157
+ ## License and citation
158
+
159
+ Original project code is available under the MIT License. Third-party software,
160
+ models and data retain their own terms, described in `NOTICE.md`.
161
+
162
+ Muhammad Allam Rafi and Cindy Rizky Afrilia. Quantitative Marking and Suture
163
+ Planning for Facial Wounds and Scars from Single Photographs: A Bioinformatic
164
+ and Deep Learning Study (2026).
165
+
166
+ * [OSF registration](https://doi.org/10.17605/OSF.IO/ESW47)
167
+ * [Zenodo archive](https://doi.org/10.5281/zenodo.24412867)
168
+
169
+ The identifiers document the research record. They do not certify clinical
170
+ performance, regulatory approval or the correctness of package outputs.
@@ -0,0 +1,123 @@
1
+ <p align="center">
2
+ <img src="assets/banner.webp" width="100%" alt="Animated rotating three dimensional facial mesh with a scan plane, a wound centre line, numbered suture marks and a millimetre counter">
3
+ </p>
4
+
5
+ <h1 align="center">Quantitative Marking and Suture Planning for Facial Wounds and Scars from Single Photographs: A Bioinformatic and Deep Learning Study</h1>
6
+
7
+ <p align="center">
8
+ Muhammad Allam Rafi<sup>1</sup> and Cindy Rizky Afrilia<sup>2</sup><br>
9
+ <sup>1</sup>Faculty of Medicine, Universitas Indonesia, Jakarta, Indonesia<br>
10
+ <sup>2</sup>Faculty of Medicine, Universitas Kristen Krida Wacana, Jakarta, Indonesia
11
+ </p>
12
+
13
+ <p align="center">
14
+ <img src="https://img.shields.io/badge/status-research%20prototype-1f3a5f?style=flat-square" alt="Research prototype">
15
+ <img src="https://img.shields.io/badge/python-3.12-1f3a5f?style=flat-square" alt="Python 3.12">
16
+ <img src="https://img.shields.io/badge/automated%20tests-90%2B-1f3a5f?style=flat-square" alt="More than 90 automated tests">
17
+ <img src="https://img.shields.io/badge/FHIR-R4B%20validated-1f3a5f?style=flat-square" alt="FHIR R4B validated">
18
+ </p>
19
+
20
+ <p align="center">
21
+ OSF DOI &nbsp;&nbsp;&nbsp;&nbsp;______________________________________________<br><br>
22
+ Zenodo DOI &nbsp;&nbsp;______________________________________________
23
+ </p>
24
+
25
+ ## Abstract
26
+
27
+ Facial wound and scar repair depends heavily on the surgeon's eye. Incision direction relative to the relaxed skin tension lines, suture spacing and order, and the choice between plasty techniques are rarely recorded as measurements, which limits teaching, audit and comparison between operators. We built an open source research prototype that turns a single photograph into a reproducible marking plan. Facial landmarks give a millimetre scale and a 34 zone atlas, a promptable segmentation model outlines the lesion, and a rule based planner drawn from textbook principles proposes closure techniques with numbered suture guides and region specific warnings. A bioinformatics layer codes findings in ICD 10 and Human Phenotype Ontology terms, exports FHIR R4B bundles and runs Reactome pathway enrichment with Benjamini Hochberg correction. More than 90 automated tests pass. A JavaScript port reproduced the Python planner in 120 of 120 randomised scenarios once two discrepancies were fixed. On a public photograph of a facial keloid, contours stayed stable under prompt perturbation (pairwise intersection over union 0.986). This shows repeatability and not accuracy. Comparison with surgeons, clinical wounds and the skin tension model has not yet been done, and the tool is not intended for clinical use.
28
+
29
+ ## Introduction
30
+
31
+ When a surgeon closes a facial laceration or revises a scar, most of the important choices are made by eye. Where the incision should lie relative to the relaxed skin tension lines, how far apart the stitches should be, where to place the first one, and whether a fusiform excision, a Z plasty or a W plasty is the better option all come from training and pattern recognition. The record of that reasoning is usually a photograph and a line of text, so it is hard to teach, to compare between operators or to audit afterwards.
32
+
33
+ Segmentation models and facial landmark detectors now run comfortably on an ordinary laptop, which makes it practical to attach a measurement and a stated rationale to every mark. This repository pairs those models with an explicit rule set taken from standard surgical teaching, and adds a bioinformatics interface so that findings can be coded, exchanged and linked to biological knowledge for research. It is a research prototype. It is meant to support a surgeon's judgement and not to replace it, and it has not been tested on patients.
34
+
35
+ ## Methods
36
+
37
+ Images are processed on the local machine. A face landmarker provides 478 points, from which the pixel to millimetre scale is derived using an iris diameter of 11.7 mm, which carries an error of about five percent, or from a manual calibration when a ruler is visible. A quality gate refuses to produce numbers when the head is turned, the eyes are closed, the image is blurred or no face is found. A facial atlas of 34 zones covers the whole oval of the face, and each analysis module reports every zone as analysed, of low confidence or not analysed together with the reason, so that no region is skipped silently.
38
+
39
+ For a wound or scar the clinician draws a rough outline. A promptable segmentation model (MobileSAM in ONNX form) snaps the outline to the tissue edge, and a consensus over seven perturbed prompts gives the final contour and a stability score. The centre line follows the principal axis of the contour. Lesions with an elongation below 2.5 or a solidity below 0.6 are treated as nonlinear, and no suture line is drawn for them, which prevents a suture guide from being laid across a lobulated keloid.
40
+
41
+ The planner compares the wound axis with the direction of the skin tension lines, which comes from a coarse rule based field that the clinician can override. An angle under 30 degrees is called favourable and one above 60 degrees unfavourable. It ranks primary layered closure, fusiform excision at a length to width ratio of 3.5, Z plasty at 30, 45 or 60 degrees with theoretical length gains of 25, 50 and 75 percent, serial Z plasty for long scars with limbs of about 15 mm, W plasty with 6 mm equilateral teeth and a geometric broken line. An ellipse is not offered when it would exceed twice the wound length. Skin sutures are laid at a 4 mm spacing with the bites 3 mm outside the wound edge and numbered in halving order, beginning at the middle or at a critical landmark such as the vermilion border. Warnings depend on the region, for example the parotid duct and facial nerve branches for a deep lateral cheek wound, the canalicular system near the medial canthus and three layer closure for a through and through lip wound. A schematic picture of the closed wound is drawn and is labelled as an illustration and not a prediction.
42
+
43
+ The bioinformatics layer suggests ICD 10 and Human Phenotype Ontology codes, with the ontology identifiers checked against the official HPO service. It writes FHIR R4B bundles that contain Observation resources with UCUM units and a Condition that is marked unconfirmed, and it validates them with the reference models before export. Over representation analysis uses a one sided hypergeometric test against the Reactome 2022 gene sets, with Benjamini Hochberg correction applied across every eligible set. A dated snapshot of gene disease associations from Open Targets is included for keloid, cleft lip, Bell palsy and acne vulgaris. A search for hypertrophic scar resolved to an unrelated cardiac disease and was therefore dropped, and every resolved disease name is now checked before it is stored.
44
+
45
+ A browser version for static hosting was written in JavaScript. It performs the planning and drawing entirely on the device and was compared with the Python implementation on 120 randomised scenarios.
46
+
47
+ A staged validation protocol is provided in the docs folder. Phase 1 recruits 45 healthy adults, 15 for each of three skin tone groups, for repeatability and for agreement with caliper measurements. The sample size follows the precision of the intraclass correlation coefficient (31 participants for an expected value of 0.85 with a confidence interval of width 0.20) and the limits of agreement (35 participants for a half width of 0.6 mm when the standard deviation of differences is 1.0 mm). Phase 2 compares the software with trained raters for palsy, cleft lip, wounds, acne and wrinkles, Phase 3 follows 30 patients before and after surgery, and the surgeon comparison tool in the application records contour overlap, the angle between skin tension lines, matched suture distances and agreement of the chosen technique, optionally with the tool output hidden until the surgeon has drawn.
48
+
49
+ ## Results
50
+
51
+ All automated tests passed, which amounts to more than 90 tests across planning geometry, wound analysis, wrinkle and acne detection, surgeon agreement metrics, bioinformatics and input robustness, together with four parity tests in Node. The parity tests compared the planner, the suture layout, the W plasty lines and the serial Z plasty between the two implementations, and they exposed two real inconsistencies in the Python code, one in the conditions for a note about long ellipses and one in the rounding of suture counts, which were corrected. Deliberately hostile input such as coincident points, polygons the size of the image, coordinates outside the picture and malformed prompts produced only controlled rejections.
52
+
53
+ On a wound simulation mannequin, a rough outline of 9 points produced a contour from which the centre line measured 52.1 mm, and the planner proposed 13 skin sutures at 4 mm and 7 deep sutures. On a public photograph of a facial keloid the contour was reproducible when the rough outline was scaled and jittered, with a mean pairwise intersection over union of 0.986 for single runs and 0.994 for the consensus. The keloid was recognised as a nonlinear lesion, no suture line was drawn and a nonsurgical first step was proposed. These figures describe how consistent repeated runs are. They do not show that the contour is correct.
54
+
55
+ A fibrosis signature of 23 collagen, growth factor and matrix genes recovered extracellular matrix organisation and collagen pathways with a false discovery rate below one in a million. Random lists of 25 and 100 genes drawn from the library produced at least one significant pathway in 0.7 and 0.3 percent of 300 draws each. An earlier version that removed pathways by observed overlap before applying the correction inflated this rate to 53 percent, which is why every eligible pathway now enters the correction. The exported FHIR bundles passed validation against the R4B models.
56
+
57
+ <p align="center">
58
+ <img src="assets/figure_marking.jpg" width="86%" alt="Three panels showing the segmented wound contour, the numbered suture marking and a schematic of the closed wound on a wound simulation mannequin">
59
+ </p>
60
+ <p align="center"><sub>Example output on a wound simulation mannequin. Left, the contour found by the segmentation model. Centre, the suture marking with numbers in halving order. Right, a schematic of the closed wound, shown as an illustration and not as a predicted outcome.</sub></p>
61
+
62
+ ## Gallery
63
+
64
+ Selected outputs from development and testing, each showing a different kind of annotation and none repeating another. Photographs were taken from Wikimedia Commons under public domain, CC BY or CC BY SA terms, and credit belongs to the original file pages. All plans are decision support examples and have not been checked by surgeons.
65
+
66
+ <table>
67
+ <tr>
68
+ <td width="50%" valign="top"><img src="assets/gallery/palsy_symmetry.jpg" width="100%" alt="Facial palsy portrait with proportions and symmetry flags against cited references."><br><sub>Facial palsy portrait with proportions and symmetry flags against cited references.</sub></td>
69
+ <td width="50%" valign="top"><img src="assets/gallery/contour_sam_vs_grabcut.jpg" width="100%" alt="Wound contour from the segmentation model in green and from the fallback method in magenta, both started from the same rough orange line."><br><sub>Wound contour from the segmentation model in green and from the fallback method in magenta, both started from the same rough orange line.</sub></td>
70
+ </tr>
71
+ <tr>
72
+ <td width="50%" valign="top"><img src="assets/gallery/keloid_nonlinear.jpg" width="100%" alt="Facial keloid recognised as a nonlinear lesion, so no suture line is drawn."><br><sub>Facial keloid recognised as a nonlinear lesion, so no suture line is drawn.</sub></td>
73
+ <td width="50%" valign="top"><img src="assets/gallery/wrinkle_map.jpg" width="100%" alt="Wrinkle map by zone on darker skin, with hair removed and unanalysed zones marked."><br><sub>Wrinkle map by zone on darker skin, with hair removed and unanalysed zones marked.</sub></td>
74
+ </tr>
75
+ <tr>
76
+ <td width="50%" valign="top"><img src="assets/gallery/acne_candidates.jpg" width="100%" alt="Colour based acne lesion candidates, to be confirmed by the clinician."><br><sub>Colour based acne lesion candidates, to be confirmed by the clinician.</sub></td>
77
+ <td width="50%" valign="top"><img src="assets/gallery/zone_atlas.jpg" width="100%" alt="The 34 zone atlas that covers the whole facial oval with no gaps."><br><sub>The 34 zone atlas that covers the whole facial oval with no gaps.</sub></td>
78
+ </tr>
79
+ </table>
80
+
81
+ ## Limitations
82
+
83
+ The skin tension field is a coarse approximation that has not been compared with a published atlas, and it should be overridden by the surgeon when it disagrees with clinical judgement. Measurements come from a single two dimensional photograph, so curved surfaces distort lengths, and the scale depends on an iris assumption unless a ruler is used. The segmentation model was trained on everyday objects, and its contours on clinical wounds have not been compared with manual outlines. The detector for red spots is based on colour alone and cannot separate acne from other red marks, since normal faces returned between 0 and 28 candidate spots while two photographs with acne returned 35 and 45. The wrinkle detector was tuned on synthetic skin and examined on a small number of photographs. The planner follows textbook rules, and it cannot see depth, blood supply, contamination, nerve injury or bone. No part of the framework has been tested against surgeons or on patients, and it must not be used to make clinical decisions.
84
+
85
+ ## Reproducibility and use
86
+
87
+ ```bash
88
+ pip install -r requirements.txt
89
+ python scripts/download_models.py
90
+ python app/server.py
91
+ ```
92
+
93
+ The application then opens at http://127.0.0.1:8791 and listens only on the local machine. The Python tests are run with the commands below, and the browser version is checked against the Python planner with Node.
94
+
95
+ ```bash
96
+ python test_surgical_planner.py
97
+ python test_bioinfo.py
98
+ python test_surgeon_compare.py
99
+ python deploy/vercel/tests/make_golden.py
100
+ node --test deploy/vercel/tests/parity.test.mjs
101
+ ```
102
+
103
+ The folder deploy/vercel holds the browser version, which can be hosted as a static site by setting the root directory of the project to deploy/vercel. The full Python application is not suited to serverless hosting because of its size and because patient photographs should not leave the clinic.
104
+
105
+ ## Availability
106
+
107
+ The code is available at https://github.com/sharing-123/facial-plastic-surgery-planner. A licence has not yet been chosen, so all rights are reserved until one is added. Photographs used during development came from public collections and are not redistributed. Persistent identifiers will be added to this page once the OSF project and the Zenodo record have been created. Third party models and data are listed in NOTICE.md.
108
+
109
+ ## Citation
110
+
111
+ ```bibtex
112
+ @software{rafi_afrilia_2026_facial_planner,
113
+ author = {Rafi, Muhammad Allam and Afrilia, Cindy Rizky},
114
+ title = {Quantitative Marking and Suture Planning for Facial Wounds and Scars from Single Photographs: A Bioinformatic and Deep Learning Study},
115
+ year = {2026},
116
+ url = {https://github.com/sharing-123/facial-plastic-surgery-planner},
117
+ note = {Research prototype. OSF DOI and Zenodo DOI to be assigned}
118
+ }
119
+ ```
120
+
121
+ ## Python package
122
+
123
+ See the [Python installation and integration guide](docs/PYPI_README.md) for the importable API, examples, tests and development instructions.
@@ -0,0 +1,53 @@
1
+ """Standard terminology codes for the findings the app produces: ICD-10 (WHO), Human Phenotype Ontology (HPO), and Open Targets
2
+ disease context from a dated snapshot.
3
+
4
+ The codes are SUGGESTIONS for a clinician or medical coder to confirm; the tool is not a diagnostic system. HPO IDs were looked up
5
+ from the official HPO API (ontology.jax.org) on 2026-11-20; ICD-10 codes are the WHO ICD-10 categories (always confirm against the
6
+ edition your institution uses, for example ICD-10-CM or ICD-10 WHO 2019)."""
7
+ import json
8
+ from pathlib import Path
9
+
10
+ DATA = Path(__file__).parent / "data"
11
+ ICD10_SYSTEM = "http://hl7.org/fhir/sid/icd-10"
12
+ HPO_SYSTEM = "http://purl.obolibrary.org/obo/hp.owl"
13
+
14
+ # open wound of the head by site (WHO ICD-10 S01.-); forehead and chin fall under 'other parts of head'
15
+ WOUND_BY_REGION = {
16
+ "periorbital": ("S01.1", "Open wound of eyelid and periocular area"), "brow": ("S01.1", "Open wound of eyelid and periocular area"),
17
+ "nose": ("S01.2", "Open wound of nose"), "cheek": ("S01.4", "Open wound of cheek and temporomandibular area"),
18
+ "lip": ("S01.5", "Open wound of lip and oral cavity"), "perioral": ("S01.5", "Open wound of lip and oral cavity"),
19
+ "forehead": ("S01.8", "Open wound of other parts of head"), "glabella": ("S01.8", "Open wound of other parts of head"),
20
+ "chin": ("S01.8", "Open wound of other parts of head"), "outside_face_oval": ("S01.8", "Open wound of other parts of head"),
21
+ }
22
+ SCAR = {
23
+ "keloid": [{"system": ICD10_SYSTEM, "code": "L91.0", "display": "Hypertrophic scar (includes keloid scar)"}, {"system": HPO_SYSTEM, "code": "HP:0010562", "display": "Keloids"}],
24
+ "hipertrofik": [{"system": ICD10_SYSTEM, "code": "L91.0", "display": "Hypertrophic scar (includes keloid scar)"}],
25
+ "other": [{"system": ICD10_SYSTEM, "code": "L90.5", "display": "Scar conditions and fibrosis of skin"}],
26
+ }
27
+ OTHER = {
28
+ "acne": [{"system": ICD10_SYSTEM, "code": "L70.0", "display": "Acne vulgaris"}, {"system": HPO_SYSTEM, "code": "HP:0001061", "display": "Acne"}],
29
+ "cleft_lip_unilateral": [{"system": ICD10_SYSTEM, "code": "Q36.9", "display": "Cleft lip, unilateral"}, {"system": HPO_SYSTEM, "code": "HP:0100333", "display": "Unilateral cleft lip"}],
30
+ "facial_palsy_bell": [{"system": ICD10_SYSTEM, "code": "G51.0", "display": "Bell's palsy"}, {"system": HPO_SYSTEM, "code": "HP:0012799", "display": "Unilateral facial palsy"}],
31
+ "skin_laceration": [{"system": HPO_SYSTEM, "code": "HP:6001125", "display": "Skin laceration"}],
32
+ }
33
+
34
+
35
+ def code_wound_or_scar(kind, region_key, scar_type=None):
36
+ """Suggested codes for a wound/scar finding. kind: 'laserasi_baru' or 'parut'."""
37
+ if kind == "laserasi_baru":
38
+ icd = WOUND_BY_REGION.get(region_key, WOUND_BY_REGION["outside_face_oval"])
39
+ return [{"system": ICD10_SYSTEM, "code": icd[0], "display": icd[1]}] + OTHER["skin_laceration"]
40
+ return SCAR.get(scar_type, SCAR["other"])
41
+
42
+
43
+ def condition_context(name):
44
+ """Open Targets snapshot entry (top associated genes with scores and provenance) or None if not in the snapshot."""
45
+ p = DATA / "opentargets_snapshot.json"
46
+ if not p.exists():
47
+ return None
48
+ snap = json.loads(p.read_text(encoding="utf-8"))
49
+ d = snap["diseases"].get(name)
50
+ if not d or "error" in d:
51
+ return None
52
+ return {**d, "retrieved": snap["retrieved"], "source": snap["source"],
53
+ "note": "gene-disease association evidence for research context; not a patient-level risk or diagnosis"}
@@ -0,0 +1,80 @@
1
+ """Over-representation analysis (ORA) of a gene list against pathway gene sets, with Benjamini-Hochberg FDR.
2
+
3
+ Typical use in this project: a research user pastes the differentially expressed genes of scar tissue (for example keloid
4
+ versus normal skin) and asks which Reactome pathways are enriched.
5
+
6
+ Method: one-sided hypergeometric test (Fisher's exact, greater) per gene set; universe = all genes present in the library (or a
7
+ user-supplied background); sets smaller than min_size or larger than max_size are skipped; p-values are adjusted by
8
+ Benjamini-Hochberg across the tested sets. Symbols not found in the universe are reported, not silently dropped.
9
+
10
+ Empirical null behaviour on random gene lists drawn from this library (measured 2026-11-20, 300 draws each, FDR <= 0.05): lists with at least
11
+ one 'significant' set: 0.7% for 25 genes, 0.3% for 100 genes (the procedure is conservative). Positive control: a keloid/fibrosis signature
12
+ recovers extracellular matrix organization and collagen pathways (FDR < 1e-6). See test_bioinfo.py.
13
+ Every eligible set (by size) enters the Benjamini-Hochberg family, including sets with no overlap. The min_overlap argument only filters
14
+ the DISPLAYED table after correction. (Filtering sets by observed overlap BEFORE correction was tried and inflated the false-positive
15
+ rate to 53% on random lists: do not do that.)
16
+
17
+ LIMITS: ORA ignores effect sizes and gene dependence, is sensitive to the background, and says nothing about causation or about an
18
+ individual patient. It is a hypothesis generator for research, not a clinical test."""
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ from scipy.stats import hypergeom
23
+
24
+ DATA = Path(__file__).parent / "data"
25
+ ALIASES = {"CTGF": "CCN2", "CYR61": "CCN1", "NOV": "CCN3"} # symbols renamed by HGNC; extend as needed
26
+
27
+
28
+ def load_library(path=None):
29
+ """Enrichr gene set text format: term, blank, then gene symbols, tab separated. Returns {term: set(genes)}."""
30
+ p = Path(path) if path else DATA / "Reactome_2022.gmt.tsv"
31
+ lib = {}
32
+ for line in p.read_text(encoding="utf-8").splitlines():
33
+ parts = line.split("\t")
34
+ if len(parts) < 3:
35
+ continue
36
+ genes = {g.strip().upper() for g in parts[2:] if g.strip()}
37
+ if genes:
38
+ lib[parts[0]] = genes
39
+ return lib
40
+
41
+
42
+ def bh_fdr(p):
43
+ """Benjamini-Hochberg adjusted p-values (monotone, capped at 1)."""
44
+ p = np.asarray(p, float)
45
+ n = len(p)
46
+ order = np.argsort(p)
47
+ ranked = p[order] * n / (np.arange(n) + 1)
48
+ adj = np.minimum.accumulate(ranked[::-1])[::-1]
49
+ out = np.empty(n)
50
+ out[order] = np.minimum(adj, 1.0)
51
+ return out
52
+
53
+
54
+ def ora(genes, library, background=None, min_size=5, max_size=500, fdr_alpha=0.05, min_overlap=3):
55
+ """genes: iterable of symbols. Returns dict with a ranked table and bookkeeping."""
56
+ query = {ALIASES.get(g.strip().upper(), g.strip().upper()) for g in genes if g and g.strip()}
57
+ universe = {g.upper() for g in background} if background is not None else set().union(*library.values())
58
+ known = query & universe
59
+ unknown = sorted(query - universe)
60
+ N, n = len(universe), len(known)
61
+ rows = []
62
+ if n == 0:
63
+ return {"table": [], "n_query": len(query), "n_in_universe": 0, "unknown_symbols": unknown, "universe_size": N}
64
+ for term, members in library.items(): # EVERY eligible set is tested; the BH family is all of them
65
+ m = members & universe
66
+ if not (min_size <= len(m) <= max_size):
67
+ continue
68
+ k = len(known & m)
69
+ p = float(hypergeom.sf(k - 1, N, len(m), n)) if k > 0 else 1.0 # P(X >= k)
70
+ odds = (k / max(n - k, 1)) / (max(len(m) - k, 1) / max(N - len(m) - (n - k), 1))
71
+ rows.append({"term": term, "overlap": k, "set_size": len(m), "p_value": p, "odds_ratio": round(odds, 2), "genes": sorted(known & m)})
72
+ if rows:
73
+ q = bh_fdr([r["p_value"] for r in rows])
74
+ for r, qq in zip(rows, q):
75
+ r["fdr"] = float(qq)
76
+ # display filter AFTER correction: filtering before it on observed overlap would inflate false positives
77
+ rows = [r for r in rows if r["overlap"] >= min_overlap]
78
+ rows.sort(key=lambda r: (r["fdr"], r["p_value"]))
79
+ return {"table": rows, "n_query": len(query), "n_in_universe": n, "unknown_symbols": unknown, "universe_size": N,
80
+ "significant": [r["term"] for r in rows if r["fdr"] <= fdr_alpha], "caveat": "hypothesis generator for research; not a clinical test"}
@@ -0,0 +1,57 @@
1
+ """Downloads the public reference data used by the bioinformatics module and stores it with provenance.
2
+
3
+ - Open Targets Platform (GraphQL): top gene-disease associations for the conditions the app deals with.
4
+ - Enrichr gene set library Reactome_2022 (Reactome pathways as gene sets), for over-representation analysis.
5
+
6
+ Run: python bioinfo/fetch_data.py (needs internet; writes bioinfo/data/*)
7
+ The snapshot is dated; re-run to refresh. Association scores are literature/data-integration evidence for RESEARCH context,
8
+ not a patient-level risk and not a diagnosis."""
9
+ import datetime
10
+ import json
11
+ import sys
12
+ import urllib.parse
13
+ import urllib.request
14
+ from pathlib import Path
15
+
16
+ DATA = Path(__file__).parent / "data"
17
+ UA = {"User-Agent": "bioinfo-fetch/1.0 (research prototype)", "Content-Type": "application/json"}
18
+ OT = "https://api.platform.opentargets.org/api/v4/graphql"
19
+ # label -> (search text, words that MUST appear in the resolved disease name; a mismatch is dropped, never stored)
20
+ CONDITIONS = {"keloid": ("keloid", ["keloid"]), "cleft lip": ("cleft lip", ["cleft", "lip"]), "Bell palsy": ("Bell palsy", ["bell"]), "acne vulgaris": ("acne vulgaris", ["acne"])}
21
+
22
+
23
+ def ot(query, variables=None):
24
+ req = urllib.request.Request(OT, data=json.dumps({"query": query, "variables": variables or {}}).encode(), headers=UA)
25
+ return json.load(urllib.request.urlopen(req, timeout=60))["data"]
26
+
27
+
28
+ def main():
29
+ DATA.mkdir(exist_ok=True)
30
+ snap = {"retrieved": datetime.date.today().isoformat(), "source": OT, "diseases": {}}
31
+ for label, (q, must) in CONDITIONS.items():
32
+ hits = ot("query($q:String!){search(queryString:$q,entityNames:[\"disease\"],page:{index:0,size:3}){hits{id name entity}}}", {"q": q})["search"]["hits"]
33
+ if not hits:
34
+ snap["diseases"][label] = {"error": "no disease found"}
35
+ continue
36
+ d = next((h for h in hits if all(w in h["name"].lower() for w in must)), None)
37
+ if d is None:
38
+ snap["diseases"][label] = {"error": "search did not resolve to a matching disease; dropped", "candidates": [h["name"] for h in hits]}
39
+ print(label, "-> NOT RESOLVED:", [h["name"] for h in hits], flush=True)
40
+ continue
41
+ rows = ot("query($id:String!){disease(efoId:$id){id name associatedTargets(page:{index:0,size:15}){count rows{score target{id approvedSymbol approvedName}}}}}", {"id": d["id"]})["disease"]
42
+ snap["diseases"][label] = {"id": rows["id"], "name": rows["name"], "n_associated_targets": rows["associatedTargets"]["count"],
43
+ "top_targets": [{"symbol": r["target"]["approvedSymbol"], "ensembl": r["target"]["id"], "name": r["target"]["approvedName"], "score": round(r["score"], 3)}
44
+ for r in rows["associatedTargets"]["rows"]]}
45
+ print(label, "->", rows["id"], rows["name"], "|", [r["target"]["approvedSymbol"] for r in rows["associatedTargets"]["rows"][:6]], flush=True)
46
+ (DATA / "opentargets_snapshot.json").write_text(json.dumps(snap, indent=1), encoding="utf-8")
47
+ lib = "Reactome_2022"
48
+ url = "https://maayanlab.cloud/Enrichr/geneSetLibrary?mode=text&libraryName=" + urllib.parse.quote(lib)
49
+ txt = urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": UA["User-Agent"]}), timeout=120).read().decode("utf-8")
50
+ (DATA / f"{lib}.gmt.tsv").write_text(txt, encoding="utf-8")
51
+ meta = {"library": lib, "source": url, "retrieved": datetime.date.today().isoformat(), "n_sets": txt.count("\n")}
52
+ (DATA / "library_meta.json").write_text(json.dumps(meta, indent=1), encoding="utf-8")
53
+ print("library:", meta)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ sys.exit(main())
@@ -0,0 +1,54 @@
1
+ """FHIR R4B export of the measurements and planned procedure, for interoperability with hospital systems.
2
+
3
+ Content: pseudonymous Patient, Observation resources with UCUM units for the measured lengths, angles, areas and suture counts,
4
+ and a Condition with suggested ICD-10/HPO codes. Everything is marked verificationStatus = unconfirmed and tagged
5
+ 'research-prototype': these are TOOL-DERIVED values for a clinician to confirm, not clinical documentation by themselves.
6
+ No image, name or identifier is included; only the pseudonym you pass in."""
7
+ import datetime
8
+ import uuid
9
+
10
+ from . import clinical_coding as cc
11
+
12
+ UCUM = "http://unitsofmeasure.org"
13
+ TAG = {"system": "https://example.org/fhir/tags", "code": "research-prototype", "display": "Tool-derived, unvalidated, clinician must confirm"}
14
+
15
+
16
+ def _obs(pid, text, value, unit, code, when, method=None):
17
+ o = {"resourceType": "Observation", "id": str(uuid.uuid4()), "meta": {"tag": [TAG]}, "status": "preliminary",
18
+ "category": [{"coding": [{"system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "exam"}]}],
19
+ "code": {"text": text}, "subject": {"reference": f"Patient/{pid}"}, "effectiveDateTime": when,
20
+ "valueQuantity": {"value": float(value), "unit": unit, "system": UCUM, "code": code}}
21
+ if method:
22
+ o["method"] = {"text": method}
23
+ return o
24
+
25
+
26
+ def build_bundle(pseudonym, report, plan, ctx, scale_note, when=None):
27
+ when = when or datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat()
28
+ region_key = (report.get("regions_crossed") or ["cheek"])[0]
29
+ pid = pseudonym
30
+ meth = f"2D photo measurement; {scale_note}"
31
+ entries = [{"resource": {"resourceType": "Patient", "id": pid, "meta": {"tag": [TAG]}}}]
32
+ obs = [_obs(pid, "Wound or scar length along centre line", report["length_mm"], "mm", "mm", when, meth),
33
+ _obs(pid, "Angle between wound axis and relaxed skin tension lines (tool estimate)", report["mean_angle_to_rstl_deg"], "degree", "deg", when, "RSTL direction set by clinician or rule-based approximation")]
34
+ if report.get("area_mm2") is not None:
35
+ obs.append(_obs(pid, "Wound or scar area", report["area_mm2"], "mm2", "mm2", when, meth))
36
+ if plan.get("rencana_jahitan"):
37
+ obs.append(_obs(pid, "Planned number of skin sutures (tool estimate)", plan["rencana_jahitan"]["perkiraan_jumlah_jahitan_kulit"], "{count}", "{count}", when, "layout from wound length and chosen spacing"))
38
+ entries += [{"resource": o} for o in obs]
39
+ coding = cc.code_wound_or_scar(ctx.get("kind", "laserasi_baru"), region_key, ctx.get("scar_type"))
40
+ cond = {"resourceType": "Condition", "id": str(uuid.uuid4()), "meta": {"tag": [TAG]},
41
+ "clinicalStatus": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/condition-clinical", "code": "active"}]},
42
+ "verificationStatus": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/condition-ver-status", "code": "unconfirmed"}]},
43
+ "code": {"coding": coding, "text": plan.get("wilayah", "")}, "subject": {"reference": f"Patient/{pid}"},
44
+ "bodySite": [{"text": plan.get("wilayah", "")}], "recordedDate": when[:10],
45
+ "note": [{"text": "Suggested codes from a research prototype; confirm before use. Primary technique suggested by the tool: "
46
+ + (plan["teknik"][0]["nama"] if plan.get("teknik") else "none")}]}
47
+ entries.append({"resource": cond})
48
+ return {"resourceType": "Bundle", "type": "collection", "timestamp": when, "meta": {"tag": [TAG]}, "entry": entries}
49
+
50
+
51
+ def validate(bundle):
52
+ """Validate against the FHIR R4B models (pydantic). Raises on structural errors; returns the parsed Bundle."""
53
+ from fhir.resources.R4B.bundle import Bundle
54
+ return Bundle.model_validate(bundle)