eshan6704 commited on
Commit
076ec0e
·
verified ·
1 Parent(s): 62f3275

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -77
app.py CHANGED
@@ -39,66 +39,25 @@ def b2_file(file_path=None, bucket_name=BUCKET_NAME, upload=True, download_path=
39
  if upload:
40
  if not file_path or not os.path.isfile(file_path):
41
  raise ValueError("Valid local file_path must be provided for upload")
42
-
43
  with open(file_path, "rb") as f:
44
  data = f.read()
45
-
46
  file_name = os.path.basename(file_path)
47
  s3.put_object(Bucket=bucket_name, Key=file_name, Body=data)
48
  return True
49
-
50
  else:
51
  if not file_path:
52
  raise ValueError("Bucket file name must be provided for download")
53
  if not download_path:
54
  raise ValueError("download_path must be provided for download")
55
-
56
  obj = s3.get_object(Bucket=bucket_name, Key=file_path)
57
  data = obj['Body'].read()
58
-
59
  with open(download_path, "wb") as f:
60
  f.write(data)
61
-
62
  return True
63
-
64
  except Exception as e:
65
  print(f"Error in B2 operation: {e}")
66
  return False
67
 
68
- def log_fetch(client, mode, req_type, name, date_str):
69
- """
70
- Append a new fetch record to the CSV in B2.
71
- """
72
- try:
73
- # Try to read existing CSV from B2
74
- try:
75
- obj = s3.get_object(Bucket=BUCKET_NAME, Key=LOG_FILE)
76
- data = obj['Body'].read()
77
- df = pd.read_csv(BytesIO(data))
78
- except Exception:
79
- df = pd.DataFrame(columns=["Sr", "Datetime", "Client", "Mode", "Req_Type", "Name", "Date"])
80
-
81
- # Append new row
82
- new_row = {
83
- "Sr": len(df) + 1,
84
- "Datetime": datetime.now().strftime("%d-%m-%Y %H:%M:%S"),
85
- "Client": client,
86
- "Mode": mode,
87
- "Req_Type": req_type,
88
- "Name": name,
89
- "Date": date_str
90
- }
91
- df = df.append(new_row, ignore_index=True)
92
-
93
- # Save back to B2
94
- csv_buffer = BytesIO()
95
- df.to_csv(csv_buffer, index=False)
96
- csv_buffer.seek(0)
97
- s3.put_object(Bucket=BUCKET_NAME, Key=LOG_FILE, Body=csv_buffer.getvalue())
98
- print("Fetch logged successfully.")
99
- except Exception as e:
100
- print(f"Error logging fetch: {e}")
101
-
102
  # ======================================================
103
  # Scrollable HTML wrapper
104
  # ======================================================
@@ -153,38 +112,15 @@ INDEX_REQ = [
153
  "index_pe_pb_div", "index_total_returns"
154
  ]
155
 
156
- # ======================================================
157
- # Update UI based on mode
158
- # ======================================================
159
- def update_on_mode(mode):
160
- if mode == "stock":
161
- return (
162
- gr.update(choices=STOCK_REQ, value="info"),
163
- gr.update(value="ITC"),
164
- gr.update(value=yesterday_str())
165
- )
166
- elif mode == "index":
167
- return (
168
- gr.update(choices=INDEX_REQ, value="indices"),
169
- gr.update(value="NIFTY 50"),
170
- gr.update(value=yesterday_str())
171
- )
172
- return (
173
- gr.update(choices=[], value=""),
174
- gr.update(value=""),
175
- gr.update(value="")
176
- )
177
-
178
  # ======================================================
179
  # Data Fetcher
180
  # ======================================================
181
  def fetch_data(mode, req_type, name, date_str):
182
- req_type = req_type.lower()
183
- name = name.strip()
184
- date_str = date_str.strip() or yesterday_str()
 
185
  date_start = last_year_date(date_str)
186
-
187
- # Detect client
188
  client = "gradio"
189
 
190
  # =====================
@@ -263,9 +199,37 @@ def fetch_data(mode, req_type, name, date_str):
263
  result = wrap(f"<h3>No valid mode: {mode}</h3>")
264
 
265
  # =====================
266
- # Log fetch in CSV
267
  # =====================
268
- log_fetch(client, mode, req_type, name, date_str)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  return result
270
 
271
  # ======================================================
@@ -276,18 +240,16 @@ with gr.Blocks(title="Stock / Index App") as iface:
276
 
277
  with gr.Row():
278
  mode_input = gr.Radio(["stock", "index"], label="Mode", value="stock", scale=1)
279
- name_input = gr.Textbox(label="Symbol / Index Name", scale=2)
280
- req_type_input = gr.Dropdown(label="Request Type", allow_custom_value=True, scale=2)
281
  date_input = gr.Textbox(label="Date (DD-MM-YYYY)", placeholder="Leave empty = yesterday", scale=1)
282
  fetch_btn = gr.Button("Fetch", scale=1)
283
 
284
  output = gr.HTML(label="Output")
285
 
286
- # Mode change → auto defaults
287
- mode_input.change(update_on_mode, inputs=mode_input, outputs=[req_type_input, name_input, date_input])
288
- iface.load(update_on_mode, inputs=mode_input, outputs=[req_type_input, name_input, date_input])
289
-
290
- # Fetch
291
  fetch_btn.click(fetch_data, inputs=[mode_input, req_type_input, name_input, date_input], outputs=output)
292
 
293
  # ======================================================
 
39
  if upload:
40
  if not file_path or not os.path.isfile(file_path):
41
  raise ValueError("Valid local file_path must be provided for upload")
 
42
  with open(file_path, "rb") as f:
43
  data = f.read()
 
44
  file_name = os.path.basename(file_path)
45
  s3.put_object(Bucket=bucket_name, Key=file_name, Body=data)
46
  return True
 
47
  else:
48
  if not file_path:
49
  raise ValueError("Bucket file name must be provided for download")
50
  if not download_path:
51
  raise ValueError("download_path must be provided for download")
 
52
  obj = s3.get_object(Bucket=bucket_name, Key=file_path)
53
  data = obj['Body'].read()
 
54
  with open(download_path, "wb") as f:
55
  f.write(data)
 
56
  return True
 
57
  except Exception as e:
58
  print(f"Error in B2 operation: {e}")
59
  return False
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # ======================================================
62
  # Scrollable HTML wrapper
63
  # ======================================================
 
112
  "index_pe_pb_div", "index_total_returns"
113
  ]
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  # ======================================================
116
  # Data Fetcher
117
  # ======================================================
118
  def fetch_data(mode, req_type, name, date_str):
119
+ mode = mode or "stock"
120
+ req_type = req_type.lower() if req_type else "info"
121
+ name = name.strip() if name else "ITC"
122
+ date_str = date_str.strip() if date_str else yesterday_str()
123
  date_start = last_year_date(date_str)
 
 
124
  client = "gradio"
125
 
126
  # =====================
 
199
  result = wrap(f"<h3>No valid mode: {mode}</h3>")
200
 
201
  # =====================
202
+ # Log fetch AFTER serving API
203
  # =====================
204
+ try:
205
+ # Read existing log
206
+ try:
207
+ obj = s3.get_object(Bucket=BUCKET_NAME, Key=LOG_FILE)
208
+ data = obj['Body'].read()
209
+ df = pd.read_csv(BytesIO(data))
210
+ except Exception:
211
+ df = pd.DataFrame(columns=["Sr","Datetime","Client","Mode","Req_Type","Name","Date"])
212
+
213
+ # Append new row
214
+ df = df.append({
215
+ "Sr": len(df)+1,
216
+ "Datetime": datetime.now().strftime("%d-%m-%Y %H:%M:%S"),
217
+ "Client": client,
218
+ "Mode": mode,
219
+ "Req_Type": req_type,
220
+ "Name": name,
221
+ "Date": date_str
222
+ }, ignore_index=True)
223
+
224
+ # Save back to B2
225
+ csv_buffer = BytesIO()
226
+ df.to_csv(csv_buffer, index=False)
227
+ csv_buffer.seek(0)
228
+ s3.put_object(Bucket=BUCKET_NAME, Key=LOG_FILE, Body=csv_buffer.getvalue())
229
+ print("Fetch logged successfully.")
230
+ except Exception as e:
231
+ print(f"Error logging fetch: {e}")
232
+
233
  return result
234
 
235
  # ======================================================
 
240
 
241
  with gr.Row():
242
  mode_input = gr.Radio(["stock", "index"], label="Mode", value="stock", scale=1)
243
+ name_input = gr.Textbox(label="Symbol / Index Name", placeholder="Enter symbol or index", scale=2)
244
+ req_type_input = gr.Dropdown(label="Request Type", choices=STOCK_REQ, value="info", allow_custom_value=True, scale=2)
245
  date_input = gr.Textbox(label="Date (DD-MM-YYYY)", placeholder="Leave empty = yesterday", scale=1)
246
  fetch_btn = gr.Button("Fetch", scale=1)
247
 
248
  output = gr.HTML(label="Output")
249
 
250
+ # =====================
251
+ # Only Fetch triggers data
252
+ # =====================
 
 
253
  fetch_btn.click(fetch_data, inputs=[mode_input, req_type_input, name_input, date_input], outputs=output)
254
 
255
  # ======================================================