-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
197 lines (154 loc) · 7.27 KB
/
app.py
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
import streamlit as st
import requests
from datetime import datetime
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
from io import BytesIO
from date_handler import *
current_date = dt.date.today()
one_year_later = current_date + dt.timedelta(days=365)
def formatted_print(item):
data = []
for obj in item:
date = datetime.fromtimestamp(
int(obj["date"]["timestamp"])).strftime("%Y-%m-%d %H:%M:%S")
temp = [date, get_time(obj, "Fajr"), get_time(obj, "Dhuhr"), get_time(
obj, "Asr"), get_time(obj, "Maghrib"), get_time(obj, "Isha")]
data.append(temp)
return data
def get_time(item, prayer):
return item["timings"][prayer].split(" ")[0]
def get_prayer_data(year, month, address):
response = requests.get(
f"http://api.aladhan.com/v1/calendarByAddress/{year}/{month}?address={address}")
if response.status_code == 200:
return formatted_print(response.json()["data"])
else:
return []
def generate_prayer_times_graph(start_month, start_year, end_month, end_year, address):
timings_data = []
month_year_list = get_month_year_range(
start_month, start_year, end_month, end_year)
for month, year in month_year_list:
timings_data.extend(get_prayer_data(year, month, address))
if not timings_data:
st.error("No data available.")
return None
df = pd.DataFrame(timings_data, columns=[
"Date", "Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"])
df["Date"] = pd.to_datetime(df["Date"], format="%Y-%m-%d %H:%M:%S")
for prayer in ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]:
df[f"{prayer}"] = pd.to_datetime(df[f"{prayer}"], format='%H:%M')
df[f"{prayer}Minutes"] = df[f"{prayer}"].apply(
lambda x: (x - datetime.combine(x.date(), datetime.min.time())).total_seconds() / 60)
plt.figure(figsize=(10, 6))
for prayer in ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]:
plt.plot(df["Date"], df[f"{prayer}Minutes"], label=prayer)
plt.xlabel("Date")
plt.ylabel("Time")
y_ticks = range(0, int(df["IshaMinutes"].max()) + 60, 60)
plt.yticks(y_ticks, [
f"{int(minutes/60):02d}:{int(minutes%60):02d}" for minutes in y_ticks])
plt.title("Prayer Timings")
plt.legend()
plt.grid()
buffer = BytesIO()
plt.savefig(buffer, format="png")
buffer.seek(0)
return buffer
# Streamlit UI
st.set_page_config(page_title="SalahGraph")
st.sidebar.title("Navigation")
page = st.sidebar.radio("Go to", ["Home", "About"])
if page == "Home":
st.title("SalahGraph: Prayer Times Visualization")
st.write(
"Generate graphs showing prayer times throughout the year with customizable options.")
# Input form for date range and address
with st.form("input_form"):
# Date and Address Inputs
start_date = st.date_input("Start Date", value=current_date)
end_date = st.date_input("End Date", value=one_year_later)
address = st.text_input("Address", value="Lombard, IL")
# Customization Inputs
graph_title = st.text_input("Graph Title", value="Prayer Timings")
x_label = st.text_input("X-Axis Label", value="Date")
y_label = st.text_input("Y-Axis Label", value="Time (minutes)")
grid_lines = st.checkbox("Show Grid Lines", value=True)
line_style = st.selectbox("Line Style", ["-", "--", "-.", ":"])
color_palette = st.selectbox(
"Color Palette", ["Default", "coolwarm", "viridis", "plasma", "cividis"])
submitted = st.form_submit_button("Generate Graph")
# Function to generate month-year ranges based on date inputs
def get_month_year_range_from_dates(start_date, end_date):
start_month = start_date.month
start_year = start_date.year
end_month = end_date.month
end_year = end_date.year
return get_month_year_range(start_month, start_year, end_month, end_year)
# Function to apply color palette
def apply_color_palette(palette, prayers):
if palette == "Default":
return {}
colors = plt.cm.get_cmap(palette, len(prayers))
return {prayer: colors(i) for i, prayer in enumerate(prayers)}
# Generate graph
if submitted:
with st.spinner("Generating graph..."):
timings_data = []
month_year_list = get_month_year_range_from_dates(
start_date, end_date)
for month, year in month_year_list:
timings_data.extend(get_prayer_data(year, month, address))
if not timings_data:
st.error("No data available.")
else:
df = pd.DataFrame(timings_data, columns=[
"Date", "Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"])
df["Date"] = pd.to_datetime(
df["Date"], format="%Y-%m-%d %H:%M:%S")
for prayer in ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]:
df[f"{prayer}"] = pd.to_datetime(
df[f"{prayer}"], format='%H:%M')
df[f"{prayer}Minutes"] = df[f"{prayer}"].apply(
lambda x: (x - datetime.combine(x.date(), datetime.min.time())).total_seconds() / 60)
# Apply color palette
colors = apply_color_palette(
color_palette, ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"])
plt.figure(figsize=(10, 6))
for prayer in ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]:
plt.plot(df["Date"], df[f"{prayer}Minutes"], label=prayer,
linestyle=line_style, color=colors.get(prayer))
plt.title(graph_title)
plt.xlabel(x_label)
plt.ylabel(y_label)
if grid_lines:
plt.grid()
y_ticks = range(0, int(df["IshaMinutes"].max()) + 60, 60)
plt.yticks(y_ticks, [
f"{int(minutes/60):02d}:{int(minutes%60):02d}" for minutes in y_ticks])
plt.legend()
buffer = BytesIO()
plt.savefig(buffer, format="png")
buffer.seek(0)
st.image(buffer, caption="Prayer Times Graph",
use_container_width=True)
elif page == "About":
st.title("About SalahGraph")
st.write("""
This project was created to help individuals visualize prayer times throughout the year. By inputting a location
and date range, users can generate customized graphs to better understand daily prayer schedules.
### Why This Project Was Created
Muslims around the world follow specific prayer times that change daily based on the location and time of the year.
This app provides a simple way to visualize these changes, helping individuals plan their routines throughout the
year, and muslim organizations/mosques plan their prayer schedules throughout the year.
### Features
- Generate prayer time graphs for any date range.
- Customizable graph titles, styles, and labels.
- Support for various locations worldwide.
- Incorporates time changes due to DST.
### Future Improvements
- Integration with geolocation services for automatic location detection.
- Enhanced styling options for the graphs.
""")