File size: 7,808 Bytes
23b1977
 
 
 
 
 
 
 
 
 
 
fa3d628
23b1977
 
 
fa3d628
 
 
 
 
 
 
23b1977
 
fa3d628
 
 
 
23b1977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa3d628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23b1977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""Construit et valide le payload de deploiement Hugging Face Space.

Le but est d'eviter la duplication entre les jobs `build` et `deploy` du
workflow GitHub Actions, et d'aligner cette logique avec la validation runtime.
"""

from __future__ import annotations

import argparse
from pathlib import Path
import shutil
import sys


PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from scripts.runtime_model_specs import (
    HISTORICAL_RUNTIME_MODEL_SPEC,
    SIMULATION_RUNTIME_MODEL_SPEC,
)

DEPLOYMENT_REQUIRED_ARTIFACTS = [
    HISTORICAL_RUNTIME_MODEL_SPEC.output_model_path.relative_to(PROJECT_ROOT),
    HISTORICAL_RUNTIME_MODEL_SPEC.output_metadata_path.relative_to(PROJECT_ROOT),
    SIMULATION_RUNTIME_MODEL_SPEC.output_model_path.relative_to(PROJECT_ROOT),
    SIMULATION_RUNTIME_MODEL_SPEC.output_metadata_path.relative_to(PROJECT_ROOT),
    Path("artifacts/experiments/experience_1/dataset_consolide_historique_colonnes.csv"),
]

PAYLOAD_DIRECTORIES = [
    Path("config"),
    Path("scripts"),
    Path("streamlit/src"),
    Path("streamlit/icones"),
    Path("data/simulation"),
    Path("artifacts/models"),
    Path("artifacts/experiments/experience_1"),
]

PAYLOAD_DIRECTORY_SPECS = [
    (Path("scripts"), Path("scripts")),
    (Path("streamlit/src"), Path("streamlit/src")),
    (Path("streamlit/icones"), Path("streamlit/icones")),
]

PAYLOAD_FILE_SPECS = [
    (Path("Dockerfile"), Path("Dockerfile")),
    (Path("config/nginx.conf"), Path("config/nginx.conf")),
    (Path("streamlit/requirements.txt"), Path("streamlit/requirements.txt")),
    (Path("data/dataset_consolide.csv"), Path("data/dataset_consolide.csv")),
    (Path("data/simulation/crop_yield.csv"), Path("data/simulation/crop_yield.csv")),
    (Path("main.py"), Path("main.py")),
    (
        HISTORICAL_RUNTIME_MODEL_SPEC.output_model_path.relative_to(PROJECT_ROOT),
        HISTORICAL_RUNTIME_MODEL_SPEC.output_model_path.relative_to(PROJECT_ROOT),
    ),
    (
        HISTORICAL_RUNTIME_MODEL_SPEC.output_metadata_path.relative_to(PROJECT_ROOT),
        HISTORICAL_RUNTIME_MODEL_SPEC.output_metadata_path.relative_to(PROJECT_ROOT),
    ),
    (
        SIMULATION_RUNTIME_MODEL_SPEC.output_model_path.relative_to(PROJECT_ROOT),
        SIMULATION_RUNTIME_MODEL_SPEC.output_model_path.relative_to(PROJECT_ROOT),
    ),
    (
        SIMULATION_RUNTIME_MODEL_SPEC.output_metadata_path.relative_to(PROJECT_ROOT),
        SIMULATION_RUNTIME_MODEL_SPEC.output_metadata_path.relative_to(PROJECT_ROOT),
    ),
    (
        Path("artifacts/experiments/experience_1/dataset_consolide_historique_colonnes.csv"),
        Path("artifacts/experiments/experience_1/dataset_consolide_historique_colonnes.csv"),
    ),
]

OPTIONAL_PAYLOAD_FILE_SPECS = [
    (Path("agriculture.png"), Path("agriculture.png")),
]

SPACE_README_CONTENT = """---
title: Rendement Agricole
emoji: 🌾
colorFrom: green
colorTo: yellow
sdk: docker
app_port: 8501
tags:
- streamlit
- agriculture
pinned: false
short_description: Démo Streamlit + FastAPI de rendement agricole
license: mit
---

# Rendement Agricole

Ce Space Docker expose une interface Streamlit connectée à une API FastAPI interne dans le même conteneur.

- UI Streamlit : port public `8501`
- API FastAPI : port interne `127.0.0.1:8000`
- logique servie : API finale `main.py` basee sur 2 modeles et 3 predictions combinees
"""


def _resolve_under(root: str | Path, relative_path: str | Path) -> Path:
    """Resout un chemin relatif a une racine de travail."""
    base_root = Path(root)
    raw_path = Path(relative_path)
    if raw_path.is_absolute():
        return raw_path
    return base_root / raw_path


def validate_deployment_artifacts(
    *,
    source_root: str | Path = PROJECT_ROOT,
) -> list[Path]:
    """Valide la presence des artefacts deployables indispensables.

    Args:
        source_root: Racine du depot a valider.

    Returns:
        list[Path]: Liste des artefacts resolus et verifies.
    """
    resolved_root = Path(source_root)
    resolved_paths = [_resolve_under(resolved_root, path) for path in DEPLOYMENT_REQUIRED_ARTIFACTS]
    missing_paths = [path for path in resolved_paths if not path.exists()]
    if missing_paths:
        formatted = ", ".join(str(path.relative_to(resolved_root)) for path in missing_paths)
        raise FileNotFoundError(
            "Missing deployment artifact in repository checkout: "
            f"{formatted}. Commit this file or regenerate it before rerunning the workflow."
        )
    return resolved_paths


def build_space_payload(
    *,
    source_root: str | Path = PROJECT_ROOT,
    output_dir: str | Path = ".hf_space_build",
) -> Path:
    """Construit le payload Docker envoye sur Hugging Face Space.

    Args:
        source_root: Racine du depot source.
        output_dir: Dossier de sortie du payload.

    Returns:
        Path: Repertoire final du payload.
    """
    resolved_root = Path(source_root)
    resolved_output_dir = _resolve_under(resolved_root, output_dir)

    if resolved_output_dir.exists():
        shutil.rmtree(resolved_output_dir)

    for directory in PAYLOAD_DIRECTORIES:
        (resolved_output_dir / directory).mkdir(parents=True, exist_ok=True)

    for source_dir, target_dir in PAYLOAD_DIRECTORY_SPECS:
        shutil.copytree(
            _resolve_under(resolved_root, source_dir),
            resolved_output_dir / target_dir,
            dirs_exist_ok=True,
        )

    for source_file, target_file in PAYLOAD_FILE_SPECS:
        destination = resolved_output_dir / target_file
        destination.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(_resolve_under(resolved_root, source_file), destination)

    for source_file, target_file in OPTIONAL_PAYLOAD_FILE_SPECS:
        resolved_source_file = _resolve_under(resolved_root, source_file)
        if resolved_source_file.exists():
            destination = resolved_output_dir / target_file
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(resolved_source_file, destination)

    (resolved_output_dir / "README.md").write_text(SPACE_README_CONTENT, encoding="utf-8")
    return resolved_output_dir


def parse_args() -> argparse.Namespace:
    """Construit l'interface CLI du script."""
    parser = argparse.ArgumentParser(
        description="Validate deployment artifacts and build the Hugging Face Space payload.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    validate_parser = subparsers.add_parser("validate", help="Validate deployable artifacts.")
    validate_parser.add_argument(
        "--source-root",
        default=str(PROJECT_ROOT),
        help="Repository root to validate.",
    )

    build_parser = subparsers.add_parser("build", help="Build the Hugging Face payload.")
    build_parser.add_argument(
        "--source-root",
        default=str(PROJECT_ROOT),
        help="Repository root used as payload source.",
    )
    build_parser.add_argument(
        "--output-dir",
        default=".hf_space_build",
        help="Output directory used for the generated payload.",
    )
    return parser.parse_args()


def main() -> None:
    """Execute la validation ou la construction du payload depuis la CLI."""
    args = parse_args()
    if args.command == "validate":
        validate_deployment_artifacts(source_root=args.source_root)
        print("[deploy] Deployment artifacts validated")
        return

    validate_deployment_artifacts(source_root=args.source_root)
    payload_dir = build_space_payload(
        source_root=args.source_root,
        output_dir=args.output_dir,
    )
    print(f"[deploy] Space payload built at {payload_dir}")


if __name__ == "__main__":
    main()