File size: 5,214 Bytes
98444eb
 
16a95a6
 
 
0cd6316
 
 
 
 
 
16a95a6
 
 
 
 
 
 
 
 
 
 
 
 
0cd6316
 
16a95a6
0cd6316
 
 
 
 
 
16a95a6
 
 
0cd6316
 
 
 
 
 
16a95a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cd6316
98444eb
 
 
 
 
3128b30
 
 
 
98444eb
 
 
 
3128b30
16a95a6
3128b30
 
 
 
 
 
 
 
 
 
16a95a6
3128b30
 
16a95a6
 
 
 
 
 
 
 
98444eb
 
16a95a6
0cd6316
16a95a6
 
 
0cd6316
 
 
16a95a6
 
 
 
 
 
 
 
 
 
 
3128b30
 
16a95a6
3128b30
98444eb
 
3128b30
98444eb
16a95a6
98444eb
16a95a6
98444eb
 
 
16a95a6
98444eb
16a95a6
98444eb
16a95a6
98444eb
3128b30
98444eb
 
 
 
 
 
3128b30
98444eb
 
3128b30
 
 
98444eb
3128b30
 
 
98444eb
16a95a6
 
 
 
 
 
 
 
 
 
98444eb
 
 
 
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
import gradio as gr
import plotly.graph_objects as go
import requests
import json

from openai import OpenAI
from dotenv import load_dotenv
from os import getenv

load_dotenv()

api_key = str(getenv("PUBLICAI_TOKEN"))
llm_model = ("swiss-ai/apertus-8b-instruct",)
llm_base_url = "https://api.publicai.co/v1"
print("Connecting to API (%d)" % len(api_key))

sys_prompt = "System prompt"
with open("data/system.md", "r") as f:
    sys_prompt = f.read()

history = [
    {"role": "assistant", "content": sys_prompt},
]
print("Read system prompt (%d bytes)" % len(sys_prompt))

client = OpenAI(
    base_url=llm_base_url,
    api_key=api_key,
)


def predict(message, history):
    history.append({"role": "user", "content": message})
    stream = client.chat.completions.create(
        messages=history, model=llm_model, stream=True
    )
    chunks = []
    for chunk in stream:
        chunks.append(chunk.choices[0].delta.content or "")
        yield "".join(chunks)


def predict2(message, history):
    if message is None or len(message) < 3:
        return None
    history.append({"role": "user", "content": message})
    r = requests.post(
        llm_base_url + "/chat/completions",
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
            "User-Agent": "BielDemain/1.0",
        },
        data=json.dumps({"model": llm_model, "messages": history}),
    )
    try:
        print(r.content)
        j = r.json()
    except Exception:
        print("Data from LLM was not understood")
        return None
    if "choices" in j and len(j["choices"]) > 0:
        return j["choices"]
        # return j["choices"][0]["message"]["content"]
    else:
        return None


map_plot = None

map_code = """
<div id="map"></div>
<script>
    var map = new maplibregl.Map({
        container: 'map',
        style: 'https://demotiles.maplibre.org/globe.json',
        center: [0, 0],
        zoom: 2
    });
</script>
"""

EXAMPLE_DACHSANIERUNG = """
Gemäss dem mir vorliegenden Amtlichen Anzeiger vom 11. November 2025 ist ein Baugesuch publiziert, das Arbeiten am Dach umfasst.

Es handelt sich dabei um einen **Dachausbau** als Teil einer Teilsanierung.

Hier sind die Details zu diesem Projekt:

* **Baugesuch Nr.:** 26’ / eBau Nr.: 2024-15579
* **Standort:** Bendicht-Rechberger-Strasse 1, 3, 5, Biel
* **Bauherrschaft:** Gewerkschaft UNIA
* **Bauvorhaben:** Das Projekt wird als "Teilsanierung Gebäude" beschrieben. Die Arbeiten beinhalten unter anderem den "Dachausbau mit Ersatz und Vergrösserung der Lukarnen".

Ich möchte weitere Informationen zu den vorgehen einen Baugesuch in Biel.
"""

EXAMPLE_AFFECTATION = """
Comment faire une Changement d’affectation à Bienne?
"""

EXAMPLE_BENCHMARK = []
with open("data/st_understanding_TEST.json", "r") as f:
    EXAMPLE_BENCHMARK = json.loads(f.read())


def chat(message, history):
    if message == "Dachausbau":
        # with map_plot.batch_update():
        # lat = 47.134169
        # lon = 7.242812
        # zoom = 14
        # map_plot.center = go.layout.mapbox.Center(lat, lon)
        # map_plot.zoom = zoom
        # gr.Plot(value=filter_map())
        return EXAMPLE_DACHSANIERUNG  # , filter_map(lat, lon, zoom)
    if message == "Changement d’affectation":
        return EXAMPLE_AFFECTATION
    elif message == "1":
        return EXAMPLE_BENCHMARK[0]["question"]
    elif message == "2":
        return EXAMPLE_BENCHMARK[1]["question"]
    elif message == "3":
        return EXAMPLE_BENCHMARK[2]["question"]
    elif message == "4":
        return EXAMPLE_BENCHMARK[4]["question"]
    return (
        "Demande-moi tout ce que tu veux savoir sur le développement urbain à Bienne. / Frag mich alles zu Stadtentwicklung in Biel.",
        # None,
    )


def filter_map(lat=47.150586, lon=7.269185, zoom=9):
    fig = go.Figure(
        go.Scattermap(
            mode="markers",
            marker=go.scattermap.Marker(size=6),
        )
    )
    fig.update_layout(
        map_style="open-street-map",
        hovermode="closest",
        map=dict(
            bearing=0,
            center=go.layout.map.Center(lat=lat, lon=lon),
            pitch=0,
            zoom=zoom,
        ),
    )
    return fig


with gr.Blocks() as demo:
    gr.Markdown("# Demo Smart City Day Biel/Bienne")
    with gr.Row():
        with gr.Column():
            reset_btn = gr.Button("Karte")
            map_plot = gr.Plot(value=filter_map())
            reset_btn.click(fn=filter_map, inputs=None, outputs=map_plot)
        with gr.Column():
            gr.Markdown(
                "Demande-moi tout ce que tu veux savoir sur le développement urbain à Bienne. / Frag mich alles zu Stadtentwicklung in Biel."
            )
            gr.ChatInterface(
                predict2,  # chat
                examples=[
                    "Dachausbau",
                    "Changement d’affectation",
                    "1 (Distance)",
                    "2 (Topology)",
                    "3 (Distance)",
                    "4 (Duration)",
                ],
                # additional_outputs=[map_plot],
                type="messages",
            )

demo.launch()