biel-demain / gradio_app.py
Oleg Lavrovsky
Initial data & README
16a95a6 unverified
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()