Srish117 commited on
Commit
2a27d21
·
verified ·
1 Parent(s): 9b08bc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +205 -45
app.py CHANGED
@@ -1,8 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import requests
3
  import pandas as pd
 
 
 
 
 
 
 
 
4
 
5
- # Your backend functions
 
 
 
 
 
 
6
  def jina(url):
7
  base_url = "https://r.jina.ai/"
8
  url = base_url + url
@@ -27,62 +129,120 @@ def price_cities(url):
27
  value_18k = value_18k.split('\n')[0]
28
 
29
  return value_24k, value_22k, value_18k
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # List of cities
31
- cities = ['Ahmedabad', 'Ayodhya', 'Bangalore', 'Bhubaneswar', 'Chandigarh', 'Chennai',
32
- 'Coimbatore', 'Delhi', 'Hyderabad', 'Jaipur', 'Kerala', 'Kolkata', 'Lucknow',
33
  'Madurai', 'Mangalore', 'Mumbai', 'Mysore', 'Nagpur', 'Nashik', 'Patna',
34
  'Pune', 'Rajkot', 'Salem', 'Surat', 'Trichy', 'Vadodara', 'Vijayawada', 'Visakhapatnam']
35
 
36
- # Sidebar content
 
 
37
  st.sidebar.title("About the Project")
38
  st.sidebar.write("This project fetches current gold rates for 24K, 22K, and 18K gold from GoodReturns for 28 Indian states. The rates for 1g, 8g, and 10g are displayed.")
39
  st.sidebar.write("**Developed by:**")
40
  st.sidebar.write("[Srish Rachamalla](https://www.linkedin.com/in/srishrachamalla/)")
41
  st.sidebar.write("[Sai Teja Pallerla](https://www.linkedin.com/in/saiteja-pallerla-668734225/)")
42
 
43
- # Main UI
44
- st.title('Gold Rates in Indian Cities')
45
- st.subheader('Select a city to view the current gold rates')
46
-
47
  # Dropdown for city selection
48
  selected_city = st.selectbox('Select a City', cities)
49
 
50
- # Fetch and display gold rates
51
- if selected_city:
52
- city_url = f"https://www.goodreturns.in/gold-rates/{selected_city}.html"
53
-
54
- # Fetch the prices using your backend function
55
- try:
56
- value_24k, value_22k, value_18k = price_cities(city_url)
57
-
58
- # Convert string values to float for calculation
59
- value_22k = round(float(value_22k.replace(',', '')),2)
60
- value_24k = round(float(value_24k.replace(',', '')),2)
61
- value_18k = round(float(value_18k.replace(',', '')),2)
62
- # Prepare data for table
63
- data = {
64
- # 'SNO': [1, 2, 3],
65
- 'Gold Purity': ['24K', '22K', '18K'],
66
- '1g Price (₹)': [value_24k, value_22k, value_18k],
67
- '8g Price (₹)': [value_24k * 8, value_22k * 8, value_18k * 8],
68
- '10g Price (₹)': [value_24k * 10, value_22k * 10, value_18k * 10]
69
- }
70
-
71
- # Create a DataFrame for display
72
- df = pd.DataFrame(data,index=[1, 2, 3])
73
-
74
- # Display the DataFrame as a table
75
- st.write(f"Gold rates in {selected_city}:")
76
- st.dataframe(df.style.format(precision=2).set_properties(**{
77
- 'background-color': 'black',
78
- 'color': 'white',
79
- 'border-color': 'ash'
80
- }))
81
-
82
-
83
- except Exception as e:
84
- st.error(f"Could not fetch the gold rates. Please try again.{e}")
85
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
87
 
88
-
 
1
+ # import streamlit as st
2
+ # import requests
3
+ # import pandas as pd
4
+
5
+ # # Your backend functions
6
+ # def jina(url):
7
+ # base_url = "https://r.jina.ai/"
8
+ # url = base_url + url
9
+ # response = requests.get(url)
10
+ # return response.text
11
+
12
+ # def price_cities(url):
13
+ # text = jina(url)
14
+ # pos1 = text.find('**')
15
+ # new = text[:pos1]
16
+
17
+ # twentytwok = new[int(new.find('22K')):int(new.find('24K'))]
18
+ # value_22k = twentytwok[int(twentytwok.find('\n\n') + 1): int(twentytwok.find('\n\n+'))][3:]
19
+ # value_22k = value_22k.split('\n')[0]
20
+
21
+ # twentyfourk = new[int(new.find('24K')):int(new.find('18K'))]
22
+ # value_24k = twentyfourk[int(twentyfourk.find('\n\n') + 1): int(twentyfourk.find('\n\n+'))][3:]
23
+ # value_24k = value_24k.split('\n')[0]
24
+
25
+ # eighteenk = new[int(new.find('18K')):]
26
+ # value_18k = eighteenk[int(eighteenk.find('\n\n') + 1): int(eighteenk.find('\n\n+'))][3:]
27
+ # value_18k = value_18k.split('\n')[0]
28
+
29
+ # return value_24k, value_22k, value_18k
30
+ # # List of cities
31
+ # cities = ['Ahmedabad', 'Ayodhya', 'Bangalore', 'Bhubaneswar', 'Chandigarh', 'Chennai',
32
+ # 'Coimbatore', 'Delhi', 'Hyderabad', 'Jaipur', 'Kerala', 'Kolkata', 'Lucknow',
33
+ # 'Madurai', 'Mangalore', 'Mumbai', 'Mysore', 'Nagpur', 'Nashik', 'Patna',
34
+ # 'Pune', 'Rajkot', 'Salem', 'Surat', 'Trichy', 'Vadodara', 'Vijayawada', 'Visakhapatnam']
35
+
36
+ # # Sidebar content
37
+ # st.sidebar.title("About the Project")
38
+ # st.sidebar.write("This project fetches current gold rates for 24K, 22K, and 18K gold from GoodReturns for 28 Indian states. The rates for 1g, 8g, and 10g are displayed.")
39
+ # st.sidebar.write("**Developed by:**")
40
+ # st.sidebar.write("[Srish Rachamalla](https://www.linkedin.com/in/srishrachamalla/)")
41
+ # st.sidebar.write("[Sai Teja Pallerla](https://www.linkedin.com/in/saiteja-pallerla-668734225/)")
42
+
43
+ # # Main UI
44
+ # st.title('Gold Rates in Indian Cities')
45
+ # st.subheader('Select a city to view the current gold rates')
46
+
47
+ # # Dropdown for city selection
48
+ # selected_city = st.selectbox('Select a City', cities)
49
+
50
+ # # Fetch and display gold rates
51
+ # if selected_city:
52
+ # city_url = f"https://www.goodreturns.in/gold-rates/{selected_city}.html"
53
+
54
+ # # Fetch the prices using your backend function
55
+ # try:
56
+ # value_24k, value_22k, value_18k = price_cities(city_url)
57
+
58
+ # # Convert string values to float for calculation
59
+ # value_22k = round(float(value_22k.replace(',', '')),2)
60
+ # value_24k = round(float(value_24k.replace(',', '')),2)
61
+ # value_18k = round(float(value_18k.replace(',', '')),2)
62
+ # # Prepare data for table
63
+ # data = {
64
+ # # 'SNO': [1, 2, 3],
65
+ # 'Gold Purity': ['24K', '22K', '18K'],
66
+ # '1g Price (₹)': [value_24k, value_22k, value_18k],
67
+ # '8g Price (₹)': [value_24k * 8, value_22k * 8, value_18k * 8],
68
+ # '10g Price (₹)': [value_24k * 10, value_22k * 10, value_18k * 10]
69
+ # }
70
+
71
+ # # Create a DataFrame for display
72
+ # df = pd.DataFrame(data,index=[1, 2, 3])
73
+
74
+ # # Display the DataFrame as a table
75
+ # st.write(f"Gold rates in {selected_city}:")
76
+ # st.dataframe(df.style.format(precision=2).set_properties(**{
77
+ # 'background-color': 'black',
78
+ # 'color': 'white',
79
+ # 'border-color': 'ash'
80
+ # }))
81
+
82
+
83
+ # except Exception as e:
84
+ # st.error(f"Could not fetch the gold rates. Please try again.{e}")
85
+
86
+ # st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
87
+
88
+
89
  import streamlit as st
90
  import requests
91
  import pandas as pd
92
+ import pymongo
93
+ import datetime
94
+ from pymongo import MongoClient
95
+ import matplotlib.pyplot as plt
96
+ import os
97
+
98
+ # Fetch the secret key from environment variables
99
+ Mongo_ip = os.getenv("Mongo_IP")
100
 
101
+
102
+ # Connect to MongoDB
103
+ client = MongoClient('mongodb+srv://srishnotebooks:[email protected]/?retryWrites=true&w=majority&appName=Goldrates')
104
+ db = client.GoldRates
105
+ collection = db['GoldRates']
106
+
107
+ # Backend functions
108
  def jina(url):
109
  base_url = "https://r.jina.ai/"
110
  url = base_url + url
 
129
  value_18k = value_18k.split('\n')[0]
130
 
131
  return value_24k, value_22k, value_18k
132
+
133
+ # Helper function to insert data only once per day (no time constraint)
134
+ def insert_data_if_not_exists(city, date, value_24k, value_22k, value_18k):
135
+ query = {"Date": date, "Place": city}
136
+ if not collection.find_one(query):
137
+ document = {
138
+ "Date": date,
139
+ "Place": city,
140
+ "GoldRate_24k": float(value_24k.replace(',', '')),
141
+ "GoldRate_22k": float(value_22k.replace(',', '')),
142
+ "GoldRate_18k": float(value_18k.replace(',', ''))
143
+ }
144
+ collection.insert_one(document)
145
+ # st.success(f"Gold rates for {city} on {date} have been saved to MongoDB.")
146
+
147
+ # Function to fetch weekly data for chart
148
+ def fetch_weekly_data(city):
149
+ today = datetime.datetime.today()
150
+ start_date = today - datetime.timedelta(days=7)
151
+ query = {"Place": city, "Date": {"$gte": start_date.strftime("%Y-%m-%d")}}
152
+ return list(collection.find(query).sort("Date", -1))
153
+
154
+ # Function to check if it's the first run of the day after 12:30 PM
155
+ def is_first_run_after_1230():
156
+ today = datetime.datetime.today()
157
+ time_check = today.replace(hour=12, minute=30, second=0, microsecond=0)
158
+ date_check = today.strftime("%Y-%m-%d")
159
+ return today >= time_check and not collection.find_one({"Date": date_check})
160
+
161
+ # Fetch and save rates for all cities
162
+ def fetch_and_save_all_cities():
163
+ date_today = datetime.datetime.today().strftime("%Y-%m-%d")
164
+ for city in cities:
165
+ city_url = f"https://www.goodreturns.in/gold-rates/{city}.html"
166
+ try:
167
+ value_24k, value_22k, value_18k = price_cities(city_url)
168
+ insert_data_if_not_exists(city, date_today, value_24k, value_22k, value_18k)
169
+ except Exception as e:
170
+ st.error(f"Could not fetch the gold rates for {city}. {e}")
171
+
172
  # List of cities
173
+ cities = ['Hyderabad', 'Ahmedabad', 'Ayodhya', 'Bangalore', 'Bhubaneswar', 'Chandigarh', 'Chennai',
174
+ 'Coimbatore', 'Delhi', 'Jaipur', 'Kerala', 'Kolkata', 'Lucknow',
175
  'Madurai', 'Mangalore', 'Mumbai', 'Mysore', 'Nagpur', 'Nashik', 'Patna',
176
  'Pune', 'Rajkot', 'Salem', 'Surat', 'Trichy', 'Vadodara', 'Vijayawada', 'Visakhapatnam']
177
 
178
+ # Main UI
179
+ st.title('Gold Rates in Indian Cities')
180
+ st.subheader('Select a city to view the current gold rates and a weekly trend.')
181
  st.sidebar.title("About the Project")
182
  st.sidebar.write("This project fetches current gold rates for 24K, 22K, and 18K gold from GoodReturns for 28 Indian states. The rates for 1g, 8g, and 10g are displayed.")
183
  st.sidebar.write("**Developed by:**")
184
  st.sidebar.write("[Srish Rachamalla](https://www.linkedin.com/in/srishrachamalla/)")
185
  st.sidebar.write("[Sai Teja Pallerla](https://www.linkedin.com/in/saiteja-pallerla-668734225/)")
186
 
 
 
 
 
187
  # Dropdown for city selection
188
  selected_city = st.selectbox('Select a City', cities)
189
 
190
+ # Generate button
191
+ if st.button("Generate Gold Rates"):
192
+ # If it's the first time after 12:30 PM, fetch and save rates for all cities
193
+ if is_first_run_after_1230():
194
+ fetch_and_save_all_cities()
195
+ st.success("Gold rates for all cities have been fetched and saved.")
196
+
197
+ # Fetch and display gold rates for the selected city
198
+ if selected_city:
199
+ date_today = datetime.datetime.today().strftime("%Y-%m-%d")
200
+ city_url = f"https://www.goodreturns.in/gold-rates/{selected_city}.html"
201
+
202
+ try:
203
+ value_24k, value_22k, value_18k = price_cities(city_url)
204
+ insert_data_if_not_exists(selected_city, date_today, value_24k, value_22k, value_18k)
205
+
206
+ # Prepare data for current rates
207
+ current_data = {
208
+ 'Gold Purity': ['24K', '22K', '18K'],
209
+ '1g Price (₹)': [float(value_24k.replace(',', '')), float(value_22k.replace(',', '')), float(value_18k.replace(',', ''))],
210
+ '8g Price (₹)': [float(value_24k.replace(',', '')) * 8, float(value_22k.replace(',', '')) * 8, float(value_18k.replace(',', '')) * 8],
211
+ '10g Price (₹)': [float(value_24k.replace(',', '')) * 10, float(value_22k.replace(',', '')) * 10, float(value_18k.replace(',', '')) * 10]
212
+ }
213
+
214
+ # Display current data
215
+ df = pd.DataFrame(current_data)
216
+ st.write(f"Gold rates in {selected_city} as of {date_today}:")
217
+ st.dataframe(df.style.format(precision=2).set_properties(**{
218
+ 'background-color': 'black',
219
+ 'color': 'white',
220
+ 'border-color': 'gray'
221
+ }))
222
+
223
+ # Weekly trend data
224
+ weekly_data = fetch_weekly_data(selected_city)
225
+ if weekly_data:
226
+ dates = [doc["Date"] for doc in weekly_data]
227
+ rates_24k = [doc["GoldRate_24k"] for doc in weekly_data]
228
+ rates_22k = [doc["GoldRate_22k"] for doc in weekly_data]
229
+ rates_18k = [doc["GoldRate_18k"] for doc in weekly_data]
230
+
231
+ # Plot weekly trends
232
+ plt.figure(figsize=(10, 5))
233
+ plt.plot(dates, rates_24k, label="24K Gold", color="gold", marker='o')
234
+ plt.plot(dates, rates_22k, label="22K Gold", color="red", marker='o')
235
+ plt.plot(dates, rates_18k, label="18K Gold", color="brown", marker='o')
236
+ plt.title(f"Gold Rates Trend in {selected_city} (Past Week)")
237
+ plt.xlabel("Date")
238
+ plt.ylabel("Price (₹)")
239
+ plt.legend()
240
+ plt.xticks(rotation=45)
241
+ st.pyplot(plt)
242
+
243
+ except Exception as e:
244
+ st.error(f"Could not fetch the gold rates. Please try again. {e}")
245
+
246
+ # Footer
247
  st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
248