Subham9126 commited on
Commit
acfe013
·
verified ·
1 Parent(s): 1537ef5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -21
app.py CHANGED
@@ -279,18 +279,23 @@ def process_stock_request(
279
 
280
  # --- FastAPI Application ---
281
 
282
- def make_json_serializable(obj):
283
- """Convert any object to JSON serializable format."""
284
- if isinstance(obj, dict):
285
- return {key: make_json_serializable(value) for key, value in obj.items()}
286
- elif isinstance(obj, list):
287
- return [make_json_serializable(item) for item in obj]
288
- elif isinstance(obj, (datetime, time)):
289
- return obj.isoformat()
290
- elif hasattr(obj, '__dict__'):
291
- return make_json_serializable(obj.__dict__)
292
- else:
293
- return obj
 
 
 
 
 
294
 
295
  api_app = FastAPI(title="Groww Stock Data API", version="1.0.0")
296
 
@@ -310,9 +315,10 @@ async def fetch_stock_data_endpoint(request: StockDataRequest):
310
  result["timestamp"] = datetime.now().isoformat()
311
 
312
  # Ensure everything is JSON serializable
313
- serializable_result = make_json_serializable(result)
314
 
315
- return serializable_result
 
316
 
317
  except Exception as e:
318
  return {
@@ -330,17 +336,20 @@ async def health_check():
330
 
331
  # --- Gradio Interface ---
332
 
333
- def execute_stock_request(ticker_input: str, start_date: str, end_date: str, interval: int) -> Dict:
334
- """Wrapper function for Gradio interface."""
335
  try:
336
  result = process_stock_request(ticker_input, start_date, end_date, interval)
337
- return result
 
338
  except Exception as e:
339
- return {
 
340
  "success": False,
341
  "error": str(e),
342
  "timestamp": datetime.now().isoformat()
343
  }
 
344
 
345
  def create_gradio_interface():
346
  """Create and configure Gradio interface."""
@@ -382,9 +391,12 @@ def create_gradio_interface():
382
  fetch_button = gr.Button("🚀 Fetch Data", variant="primary")
383
 
384
  with gr.Column():
385
- output_box = gr.JSON(
386
- label="API Response",
387
- show_label=True
 
 
 
388
  )
389
 
390
  gr.Markdown("""
 
279
 
280
  # --- FastAPI Application ---
281
 
282
+ def safe_json_serialize(obj):
283
+ """Safely serialize any object to JSON string."""
284
+ def default_serializer(o):
285
+ if isinstance(o, (datetime, time)):
286
+ return o.isoformat()
287
+ elif hasattr(o, '__dict__'):
288
+ return o.__dict__
289
+ elif hasattr(o, 'to_dict'):
290
+ return o.to_dict()
291
+ else:
292
+ return str(o)
293
+
294
+ try:
295
+ return json.dumps(obj, indent=2, default=default_serializer, ensure_ascii=False)
296
+ except Exception as e:
297
+ # Fallback: convert everything to strings
298
+ return json.dumps(str(obj), indent=2)
299
 
300
  api_app = FastAPI(title="Groww Stock Data API", version="1.0.0")
301
 
 
315
  result["timestamp"] = datetime.now().isoformat()
316
 
317
  # Ensure everything is JSON serializable
318
+ serializable_result = safe_json_serialize(result)
319
 
320
+ # Parse back to dict for API response
321
+ return json.loads(serializable_result)
322
 
323
  except Exception as e:
324
  return {
 
336
 
337
  # --- Gradio Interface ---
338
 
339
+ def execute_stock_request(ticker_input: str, start_date: str, end_date: str, interval: int) -> str:
340
+ """Wrapper function for Gradio interface - returns JSON string for compatibility."""
341
  try:
342
  result = process_stock_request(ticker_input, start_date, end_date, interval)
343
+ # Use safe serialization to avoid any JsonData issues
344
+ return safe_json_serialize(result)
345
  except Exception as e:
346
+ logger.error(f"Error in execute_stock_request: {e}")
347
+ error_result = {
348
  "success": False,
349
  "error": str(e),
350
  "timestamp": datetime.now().isoformat()
351
  }
352
+ return safe_json_serialize(error_result)
353
 
354
  def create_gradio_interface():
355
  """Create and configure Gradio interface."""
 
391
  fetch_button = gr.Button("🚀 Fetch Data", variant="primary")
392
 
393
  with gr.Column():
394
+ output_box = gr.Textbox(
395
+ label="API Response (JSON)",
396
+ lines=20,
397
+ max_lines=30,
398
+ show_copy_button=True,
399
+ container=True
400
  )
401
 
402
  gr.Markdown("""