File size: 1,691 Bytes
60b99bb
 
 
 
 
 
 
 
 
 
18422d2
60b99bb
 
3936ffe
 
 
 
60b99bb
 
 
 
 
 
 
 
 
 
 
 
 
18422d2
 
60b99bb
 
 
 
 
 
 
3936ffe
60b99bb
 
 
 
 
 
 
 
 
 
18422d2
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
import re

import leafmap.maplibregl as leafmap
import pandas as pd
import streamlit as st
from ibis import _


def execute_prompt(con, chain, prompt):
    response = chain.invoke({"question": prompt})
    st.write(response.replace("testing", "crops"))
    gdf = as_geopandas(con, response)

    if len(gdf) == 0:
        st.write("No results found.")
        return

    if 'geometry' in gdf.columns:
        m = leafmap.Map()
        m.add_gdf(gdf)
        m.to_streamlit()
    else:
        gdf.drop(columns=['geometry', 'bbox', 'bbox.minx', 'bbox.maxx', 'bbox.miny', 'bbox.maxy'], errors='ignore', inplace=True)
        st.dataframe(pd.DataFrame(gdf), column_config={
            "area": st.column_config.NumberColumn("Area (ha)", format="%.5f"),
            "perimeter": st.column_config.NumberColumn("Perimeter (m)", format="%.3f"),
            "determination_datetime": st.column_config.DatetimeColumn("Determination Date"),
        })

def as_geopandas(con, response):
    #import code; code.interact(local=locals())
    response = re.sub(";$", "", response).replace("testing", "crops")
    sql_query = f"CREATE OR REPLACE VIEW testing AS ({response})"
    con.raw_sql(sql_query)
    gdf = con.table("testing")

    if 'geometry' in gdf.columns:
        gdf = (gdf
               .cast({"geometry": "geometry"})
               # .mutate(geometry = _.geometry.convert("EPSG:4326", "EPSG:4326"))
               .to_pandas()
              ).set_crs(epsg=4326, inplace=True) 
    else:
        gdf = gdf.to_pandas()

    for col in gdf.columns:
        dtype = str(gdf[col].dtype)
        if dtype.startswith("datetime64"):
            gdf[col] = gdf[col].astype(str)
    
    return gdf