File size: 8,293 Bytes
b10dbaa
 
 
 
 
6d4d03f
ebc2ece
b10dbaa
a8969c3
b10dbaa
01defef
b10dbaa
 
01defef
1df563c
b10dbaa
01defef
b10dbaa
 
01defef
b10dbaa
 
49d14ca
 
 
 
e2c81e5
49d14ca
 
 
 
 
edb7355
01defef
edb7355
a472331
 
 
edb7355
01defef
ebc2ece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4d03f
 
 
b10dbaa
 
01defef
b10dbaa
01defef
b10dbaa
 
bbbf293
01defef
b10dbaa
bbbf293
 
b10dbaa
01defef
b10dbaa
01defef
 
 
 
6d4d03f
 
 
b10dbaa
6d4d03f
8a8cff3
 
 
 
 
96da45a
8a8cff3
caddedc
 
 
 
 
 
 
6d4d03f
 
 
 
 
 
 
 
8a8cff3
 
 
1df563c
a472331
 
8a8cff3
 
96da45a
8a8cff3
96da45a
8a8cff3
96da45a
caddedc
1fb0b3b
96da45a
6d4d03f
 
 
15d58ea
8a8cff3
1df563c
15d58ea
1df563c
 
 
 
 
 
 
 
b10dbaa
6d4d03f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caddedc
8a8cff3
1fb0b3b
683e869
6d4d03f
01defef
b10dbaa
4482a4e
b10dbaa
01defef
0db7492
4482a4e
6d4d03f
b10dbaa
ebc2ece
 
 
 
 
b10dbaa
 
1e7a1cd
bbbf293
01defef
 
 
 
 
 
 
bbbf293
 
 
 
15d58ea
bbbf293
 
 
 
1e7a1cd
01defef
 
 
 
 
 
 
49d14ca
 
 
 
d8404d9
49d14ca
d8404d9
bfad8fc
15d58ea
49d14ca
 
 
b10dbaa
 
4482a4e
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import folium
import streamlit as st
import pandas as pd
from streamlit_folium import st_folium
import time
import requests
from utils import legend_macro

st.set_page_config(layout="wide", initial_sidebar_state="collapsed")

if "sleep_time" not in st.session_state:
    st.session_state.sleep_time = 2

if "auto_refresh" not in st.session_state:
    st.session_state.auto_refresh = False

auto_refresh = st.sidebar.checkbox("Auto Refresh?", st.session_state.auto_refresh)

if auto_refresh:
    number = st.sidebar.number_input("Refresh rate in seconds", value=st.session_state.sleep_time)
    st.session_state.sleep_time = number

#Logo
st.markdown(
    """
    <div style="text-align: center;">
    <img src="https://storage.googleapis.com/storage-annarabic/Nt3awnou(1).png" width="200" height="200">
    </div>
    """,
    unsafe_allow_html=True,
)

st.title("Nt3awnou نتعاونو ")

st.markdown("""
📝 Help us report more people in need by filling this form: https://forms.gle/nZNCUVog9ka2Vdqu6 : ساعدونا نبلغو الناس ليمحتاجين فهاد الاستمارة

✉️ [email protected] المتطوعين ليبغاو يعاونوا يقدرو يتصلوا معنا عبر البريد  
            """)

session = requests.Session()
@st.cache_data(persist=True)
def parse_latlng_from_link(url):
    try:
        # extract latitude and longitude from gmaps link 
        if "@" not in url:
            # We first need to get the redirect URL
            resp = session.head(url, allow_redirects=True)
            url = resp.url
        latlng = url.split('@')[1].split(',')[0:2]
        return [float(latlng[0]), float(latlng[1])]
    except Exception as e:
        print(f"Error parsing latlng from link: {e}")
        return None
    
def parse_gg_sheet_interventions(url):
    df = pd.read_csv(url)
    return df.assign(latlng=df.iloc[:, 3].apply(parse_latlng_from_link))

def parse_gg_sheet(url):
    url = url.replace("edit#gid=", "export?format=csv&gid=")
    df = pd.read_csv(url)

    # parse latlng (column 4) to [lat, lng]
    def parse_latlng(latlng):
        try:
            lat, lng = latlng.split(",")
            return [float(lat), float(lng)]
        except Exception as e:
            print(f"Error parsing latlng: {e}")
            return None

    return df.assign(latlng=df.iloc[:, 4].apply(parse_latlng))

df = parse_gg_sheet(
    "https://docs.google.com/spreadsheets/d/1gYoBBiBo1L18IVakHkf3t1fOGvHWb23loadyFZUeHJs/edit#gid=966953708"
)
interventions_df = parse_gg_sheet_interventions(
    "https://docs.google.com/spreadsheets/d/1eXOTqunOWWP8FRdENPs4cU9ulISm4XZWYJJNR1-SrwY/gviz/tq?tqx=out:csv"
)

# select requests
headers_mapping = {
    "إغاثة": "Rescue/إغاثة",
    "مساعدة طبية": "Medical Assistance/مساعدة طبية",
    "مأوى": "Shelter/مأوى",
    "طعام وماء": "Food & Water/طعام وماء",
    "مخاطر (تسرب الغاز، تلف في الخدمات العامة...)": "Danger/مخاطر (تسرب الغاز، تلف في الخدمات العامة...)",
}
colors_mapping = {
    "إغاثة": "red",
    "مساعدة طبية": "orange",
    "مأوى": "yellow",
    "طعام وماء": "blue",
    "مخاطر (تسرب الغاز، تلف في الخدمات العامة...)": "grey",
}
icon_mapping = {
    "إغاثة": "bell",        # life ring icon for rescue
    "مساعدة طبية": "heart",     # medical kit for medical assistance
    "مأوى": "home",              # home icon for shelter
    "طعام وماء": "cutlery",      # cutlery (fork and knife) for food & water
    "مخاطر (تسرب الغاز، تلف في الخدمات العامة...)": "Warning"  # warning triangle for dangers
}

options = ["إغاثة", "مساعدة طبية", "مأوى", "طعام وماء", "مخاطر (تسرب الغاز، تلف في الخدمات العامة...)"]
selected_options = []

st.markdown("👉 **Choose request type / اختر نوع الطلب**")
col1, col2, col3, col4, col5 = st.columns([2, 3, 2, 3, 4])
cols = [col1, col2, col3, col4, col5]

for i, option in enumerate(options):
    checked = cols[i].checkbox(headers_mapping[option], value=True)
    if checked:
        selected_options.append(headers_mapping[option])

arabic_options = [e.split("/")[1] for e in selected_options]
df['id'] = df.index
filtered_df = df[df['ما هي احتياجاتك؟ (أضفها إذا لم يتم ذكرها)'].isin(arabic_options)]
selected_headers = [headers_mapping[request] for request in arabic_options]

# select interventions
st.markdown("👇 **View past or planned interventions / عرض عمليات المساعدة السابقة أو المخطط لها**")
show_interventions = st.checkbox("Display Interventions عرض التدخلات", value=True)

m = folium.Map(
    location=[31.228674, -7.992047],
    zoom_start=8.5,
    min_zoom=8.5,
    max_lat=35.628674,
    min_lat=29.628674,
    max_lon=-4.992047,
    min_lon=-10.992047,
    max_bounds=True,
)

if show_interventions:
    for index, row in interventions_df.iterrows():
        status = "Done ✅" if row[interventions_df.columns[5]]=="Intervention prévue dans le futur / Planned future intervention" else "Planned ⌛"
        color_mk = "green" if row[interventions_df.columns[5]]=="Intervention prévue dans le futur / Planned future intervention" else "pink"
        intervention_type = row[interventions_df.columns[6]].split("/")[0].strip()
        org = row[interventions_df.columns[1]]
        city = row[interventions_df.columns[9]]
        date = row[interventions_df.columns[4]]
        intervention_info = f"<b>Status:</b> {status}<br><b>Org:</b> {org}<br><b>Intervention:</b> {intervention_type}<br><b>📅 Date:</b> {date}"
        print(f"intervention_info: {intervention_info}")
        folium.Marker(
            location=row["latlng"],
            tooltip=city,
            popup=folium.Popup(intervention_info, max_width=300),  
            icon=folium.Icon(color=color_mk)  
        ).add_to(m)

for index, row in filtered_df.iterrows():
    request_type = row['ما هي احتياجاتك؟ (أضفها إذا لم يتم ذكرها)']
    display_text = f"<b>Request Type:</b> {request_type}<br><b>Id:</b> {row['id']}"
    icon_name = icon_mapping.get(request_type, 'info-sign') 
    if row["latlng"] is None:
        continue

    folium.Marker(
        location=row["latlng"],
        tooltip=row['  لأي  جماعة / قيادة / دوار تنتمون ؟'] if not pd.isna(row['  لأي  جماعة / قيادة / دوار تنتمون ؟']) else None,
        popup=folium.Popup(display_text, max_width=300),  
        icon=folium.Icon(color=colors_mapping.get(request_type, "blue"), icon=icon_name)  
    ).add_to(m)


# Macro to add legend
m.get_root().add_child(legend_macro)

st_data = st_folium(m, use_container_width=True)

# Google Sheet Table
st.subheader("📝 **Table of requests / جدول الطلبات**")
st.markdown(
    """
    <iframe src="https://docs.google.com/spreadsheets/d/1gYoBBiBo1L18IVakHkf3t1fOGvHWb23loadyFZUeHJs/" width="100%" height="600px"></iframe>
    """,
    unsafe_allow_html=True,
)

# Google Sheet Table
st.subheader("📝 **Table of interventions / جدول التدخلات**")
st.markdown(
    """
    <iframe src="https://docs.google.com/spreadsheets/d/1eXOTqunOWWP8FRdENPs4cU9ulISm4XZWYJJNR1-SrwY/?single=true&gid=419657423&range=f2:g6&widget=false&chrome=false" width="100%" height="600px"></iframe>
    """,
    unsafe_allow_html=True,
)

# Google Form
# st.markdown(
#     """
#     <iframe src="https://docs.google.com/forms/d/e/1FAIpQLSfNrFHUScot5jQyRUJmor7kWYgwkkME6WqRgQG_L4Eze4RdHA/viewform?embedded=true" width="640" height="2877" frameborder="0" marginheight="0" marginwidth="0">Loading…</iframe>
#     """,
#     unsafe_allow_html=True,
# )


# Credits
st.markdown(
    """
    <hr>
    <div style="text-align: center;">
    <p>By <b>Moroccans</b> for <b>Moroccans</b> 🤝</p>
    <p>Bot powered by <a href="https://www.annarabic.com/">Annarabic</a></p>
    <p>Collaboration made possible thanks to <a href="https://summerschool.morocco.ai/">AI Summer School</a></p>
    """,
    unsafe_allow_html=True,
)
if auto_refresh:
    time.sleep(number)
    st.experimental_rerun()