1+ from __future__ import annotations
2+
3+ import os
4+ import tempfile
5+ import time
6+ from typing import NoReturn
7+
8+ from optuna .artifacts import FileSystemArtifactStore
9+ from optuna .artifacts import upload_artifact
10+ from optuna_dashboard import register_preference_feedback_component
11+ from optuna_dashboard .preferential import create_study
12+ from optuna_dashboard .preferential .samplers .gp import PreferentialGPSampler
13+ from PIL import Image , ImageEnhance
14+
15+
16+ STORAGE_URL = "sqlite:///db.sqlite3"
17+ artifact_path = os .path .join (os .path .dirname (__file__ ), "artifact" )
18+ artifact_store = FileSystemArtifactStore (base_path = artifact_path )
19+ os .makedirs (artifact_path , exist_ok = True )
20+
21+
22+ def main () -> NoReturn :
23+ study = create_study (
24+ n_generate = 4 ,
25+ study_name = "Preferential Optimization Image Scene" ,
26+ storage = STORAGE_URL ,
27+ sampler = PreferentialGPSampler (),
28+ load_if_exists = True ,
29+ )
30+ # Change the component, displayed on the human feedback pages.
31+ # By default (component_type="note"), the Trial's Markdown note is displayed.
32+ user_attr_key = "rgb_image"
33+ register_preference_feedback_component (study , "artifact" , user_attr_key )
34+
35+ with tempfile .TemporaryDirectory () as tmpdir :
36+ while True :
37+ # If study.should_generate() returns False,
38+ # the generator waits for human evaluation.
39+ if not study .should_generate ():
40+ time .sleep (0.1 ) # Avoid busy-loop
41+ continue
42+
43+ trial = study .ask ()
44+ # 1. Ask new parameters
45+ contrast_factor = trial .suggest_float ("contrast_factor" , 0.0 , 2.0 )
46+ brightness_factor = trial .suggest_float ("brightness_factor" , 0.0 , 2.0 )
47+ color_factor = trial .suggest_float ("color_factor" , 0.0 , 2.0 )
48+ sharpness_factor = trial .suggest_float ("sharpness_factor" , 0.0 , 2.0 )
49+
50+ # 2. Generate image
51+ image_path = os .path .join (tmpdir , f"sample-{ trial .number } .png" )
52+ image = Image .open ("sample.png" )
53+
54+ # Adjust contrast
55+ image = ImageEnhance .Contrast (image ).enhance (contrast_factor )
56+ # Adjust brightness
57+ image = ImageEnhance .Brightness (image ).enhance (brightness_factor )
58+ # Adjust color
59+ image = ImageEnhance .Color (image ).enhance (color_factor )
60+ # Adjust sharpness
61+ image = ImageEnhance .Sharpness (image ).enhance (sharpness_factor )
62+
63+ image .save (image_path )
64+
65+ # 3. Upload Artifact and set artifact_id to trial.user_attrs["rgb_image"].
66+ artifact_id = upload_artifact (trial , image_path , artifact_store )
67+ trial .set_user_attr (user_attr_key , artifact_id )
68+
69+
70+ if __name__ == "__main__" :
71+ main ()
0 commit comments