File size: 2,256 Bytes
4928e14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
import onnxruntime as ort
import json
from cryptography.fernet import Fernet
import os

# Model load
key = os.getenv("ARTER_MODEL_KEY")
cipher = Fernet(key)

with open("model.bin", "rb") as f:
    encrypted = f.read()
    decrypted = cipher.decrypt(encrypted)
    ort_session = ort.InferenceSession(decrypted)

# Initialize ONNX session
input_name = ort_session.get_inputs()[0].name

def softmax(x):
    return np.exp(x) / np.sum(np.exp(x), axis=1)

# Load mappings
with open("species_to_idx.json", "r") as f:
    species_to_idx = json.load(f)

with open("idx_to_target.json", "r") as f:
    idx_to_target = json.load(f)
    
target_list = list(idx_to_target.keys())

def predict(species):
    
    if not species:
        return {}, {}, {}
    
    input = [species_to_idx[s] for s in species]
    input_np = np.array(input, dtype=np.int64).reshape(1, -1)

    output = ort_session.run([], {input_name: input_np})
    output = {target: softmax(output[i]) for i, target in enumerate(target_list)}
    
    format_output = []
    
    for target in target_list:
        probs = output[target][0]
        classes = idx_to_target[target]
        format_output.append({classes[str(i)]: float(p) for i, p in enumerate(probs)})
    
    return format_output

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("## Naturtype og §3 klassifikation baseret på artsfund")
    gr.Markdown("Dette værktøj analyserer artsregistreringer for at bestemme et områdes hovednaturtype, naturtilstand og om området er omfattet af Naturbeskyttelseslovens paragraf 3.")

    with gr.Row():
        choices = sorted(species_to_idx.keys())
        species_dropdown = gr.Dropdown(
            choices=choices,
            multiselect=True,
            label="Vælg arter",
        )
    
    with gr.Row():
        naturtype = gr.Label("", label="Hovednaturtype")
        p3 = gr.Label("", label="§3 område")
        tilstand = gr.Label("", label="Naturtilstand")

    gr.Markdown("App og model af Kenneth Thorø Martinsen (kenneth2810@gmail.com).")

    species_dropdown.change(
        predict,
        inputs=[species_dropdown],
        outputs=[naturtype, p3, tilstand]
    )

if __name__ == "__main__":
    demo.launch()