Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,7 @@ import pytz
|
|
| 8 |
import tzlocal
|
| 9 |
import logging
|
| 10 |
import json
|
|
|
|
| 11 |
|
| 12 |
# --- Basic Setup ---
|
| 13 |
|
|
@@ -24,7 +25,7 @@ class DateTimeValidationError(ValueError):
|
|
| 24 |
hist_url = "https://groww.in/v1/api/charting_service/v2/chart/exchange/NSE/segment/CASH"
|
| 25 |
|
| 26 |
|
| 27 |
-
# --- Date/Time Functions ---
|
| 28 |
|
| 29 |
def validate_datetime_format(dt_str: str) -> datetime:
|
| 30 |
"""Validate datetime string in strict 'YYYY-MM-DD' format."""
|
|
@@ -71,7 +72,7 @@ def get_time_range_in_unix_ms(start_date_str: str, end_date_str: str, timezone:
|
|
| 71 |
return {"start_timestamp_ms": start_timestamp, "end_timestamp_ms": end_timestamp}
|
| 72 |
|
| 73 |
|
| 74 |
-
# --- Asynchronous API
|
| 75 |
|
| 76 |
async def call_price_api_async(session: aiohttp.ClientSession, ticker: str, start: int, end: int, interval: int) -> Dict:
|
| 77 |
"""Asynchronously calls the candle API."""
|
|
@@ -85,9 +86,6 @@ async def call_price_api_async(session: aiohttp.ClientSession, ticker: str, star
|
|
| 85 |
except aiohttp.ClientError as e:
|
| 86 |
return {"ticker": ticker, "interval": interval, "data": None, "error": str(e)}
|
| 87 |
|
| 88 |
-
|
| 89 |
-
# --- Main Processing Logic ---
|
| 90 |
-
|
| 91 |
async def main_task(tickers: List[str], start_time: int, end_time: int, intervals: List[int], progress: gr.Progress):
|
| 92 |
"""Main function to run the asynchronous API calls in batches."""
|
| 93 |
results = []
|
|
@@ -124,17 +122,33 @@ def process_and_merge_data(results: list) -> str:
|
|
| 124 |
|
| 125 |
return json.dumps(list(merged_data.values()), indent=4)
|
| 126 |
|
| 127 |
-
|
|
|
|
| 128 |
|
| 129 |
async def run_backend_processing(tickers_text: str, progress=gr.Progress(track_tqdm=True)):
|
| 130 |
"""The main function to be called by the Gradio interface."""
|
| 131 |
if not tickers_text.strip():
|
| 132 |
-
yield "Please
|
| 133 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
tickers = [ticker.strip().upper() for ticker in tickers_text.split('\n') if ticker.strip()]
|
| 136 |
today_str = date.today().strftime("%Y-%m-%d")
|
| 137 |
-
yield f"Starting processing for {len(tickers)} tickers
|
| 138 |
|
| 139 |
try:
|
| 140 |
time_range = get_time_range_in_unix_ms(today_str, today_str)
|
|
@@ -153,19 +167,20 @@ async def run_backend_processing(tickers_text: str, progress=gr.Progress(track_t
|
|
| 153 |
logger.error(f"An unhandled error occurred: {e}")
|
| 154 |
yield f"An error occurred: {e}", "{}"
|
| 155 |
|
| 156 |
-
|
|
|
|
| 157 |
|
| 158 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 159 |
gr.Markdown("## Stock Data Backend Processor")
|
| 160 |
-
gr.Markdown("Enter
|
| 161 |
|
| 162 |
with gr.Row():
|
| 163 |
with gr.Column(scale=1):
|
| 164 |
-
#
|
| 165 |
tickers_input = gr.Textbox(
|
| 166 |
-
lines=
|
| 167 |
-
label=
|
| 168 |
-
value="RELIANCE
|
| 169 |
)
|
| 170 |
start_button = gr.Button("Start Processing", variant="primary")
|
| 171 |
|
|
@@ -174,16 +189,17 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 174 |
json_output = gr.JSON(label="Processed JSON Output")
|
| 175 |
|
| 176 |
# --- Triggers ---
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
| 187 |
|
| 188 |
if __name__ == "__main__":
|
| 189 |
demo.launch()
|
|
|
|
| 8 |
import tzlocal
|
| 9 |
import logging
|
| 10 |
import json
|
| 11 |
+
import ast # Import the ast module for safe string evaluation
|
| 12 |
|
| 13 |
# --- Basic Setup ---
|
| 14 |
|
|
|
|
| 25 |
hist_url = "https://groww.in/v1/api/charting_service/v2/chart/exchange/NSE/segment/CASH"
|
| 26 |
|
| 27 |
|
| 28 |
+
# --- Date/Time Functions (No changes here) ---
|
| 29 |
|
| 30 |
def validate_datetime_format(dt_str: str) -> datetime:
|
| 31 |
"""Validate datetime string in strict 'YYYY-MM-DD' format."""
|
|
|
|
| 72 |
return {"start_timestamp_ms": start_timestamp, "end_timestamp_ms": end_timestamp}
|
| 73 |
|
| 74 |
|
| 75 |
+
# --- Asynchronous API & Processing Functions (No changes here) ---
|
| 76 |
|
| 77 |
async def call_price_api_async(session: aiohttp.ClientSession, ticker: str, start: int, end: int, interval: int) -> Dict:
|
| 78 |
"""Asynchronously calls the candle API."""
|
|
|
|
| 86 |
except aiohttp.ClientError as e:
|
| 87 |
return {"ticker": ticker, "interval": interval, "data": None, "error": str(e)}
|
| 88 |
|
|
|
|
|
|
|
|
|
|
| 89 |
async def main_task(tickers: List[str], start_time: int, end_time: int, intervals: List[int], progress: gr.Progress):
|
| 90 |
"""Main function to run the asynchronous API calls in batches."""
|
| 91 |
results = []
|
|
|
|
| 122 |
|
| 123 |
return json.dumps(list(merged_data.values()), indent=4)
|
| 124 |
|
| 125 |
+
|
| 126 |
+
# --- Gradio Backend Function (MODIFIED FOR NEW INPUT FORMAT) ---
|
| 127 |
|
| 128 |
async def run_backend_processing(tickers_text: str, progress=gr.Progress(track_tqdm=True)):
|
| 129 |
"""The main function to be called by the Gradio interface."""
|
| 130 |
if not tickers_text.strip():
|
| 131 |
+
yield "Error: Input is empty. Please provide a list of tickers.", "{}"
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
# Safely parse the string input into a Python list
|
| 136 |
+
parsed_input = ast.literal_eval(tickers_text)
|
| 137 |
+
if not isinstance(parsed_input, list):
|
| 138 |
+
raise TypeError("Input must be a list.")
|
| 139 |
+
# Clean and validate tickers
|
| 140 |
+
tickers = [str(item).strip().upper() for item in parsed_input]
|
| 141 |
+
if not tickers:
|
| 142 |
+
yield "Error: The provided list is empty.", "{}"
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
except (ValueError, SyntaxError, TypeError) as e:
|
| 146 |
+
error_message = 'Invalid input format. Please provide a list of strings, e.g., ["RELIANCE", "INFY"]'
|
| 147 |
+
yield error_message, "{}"
|
| 148 |
+
return
|
| 149 |
|
|
|
|
| 150 |
today_str = date.today().strftime("%Y-%m-%d")
|
| 151 |
+
yield f"Starting processing for {len(tickers)} tickers: {tickers}", "{}"
|
| 152 |
|
| 153 |
try:
|
| 154 |
time_range = get_time_range_in_unix_ms(today_str, today_str)
|
|
|
|
| 167 |
logger.error(f"An unhandled error occurred: {e}")
|
| 168 |
yield f"An error occurred: {e}", "{}"
|
| 169 |
|
| 170 |
+
|
| 171 |
+
# --- Gradio UI (MODIFIED FOR NEW INPUT FORMAT) ---
|
| 172 |
|
| 173 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 174 |
gr.Markdown("## Stock Data Backend Processor")
|
| 175 |
+
gr.Markdown("Enter a list of stock tickers in Python list format.")
|
| 176 |
|
| 177 |
with gr.Row():
|
| 178 |
with gr.Column(scale=1):
|
| 179 |
+
# Update textbox to be single-line and show the correct example format
|
| 180 |
tickers_input = gr.Textbox(
|
| 181 |
+
lines=1,
|
| 182 |
+
label='Enter Tickers as a List',
|
| 183 |
+
value='["RELIANCE", "INFY"]'
|
| 184 |
)
|
| 185 |
start_button = gr.Button("Start Processing", variant="primary")
|
| 186 |
|
|
|
|
| 189 |
json_output = gr.JSON(label="Processed JSON Output")
|
| 190 |
|
| 191 |
# --- Triggers ---
|
| 192 |
+
# Trigger on button click or pressing Enter in the textbox
|
| 193 |
+
start_button.click(
|
| 194 |
+
fn=run_backend_processing,
|
| 195 |
+
inputs=[tickers_input],
|
| 196 |
+
outputs=[logs_output, json_output]
|
| 197 |
+
)
|
| 198 |
+
tickers_input.submit(
|
| 199 |
+
fn=run_backend_processing,
|
| 200 |
+
inputs=[tickers_input],
|
| 201 |
+
outputs=[logs_output, json_output]
|
| 202 |
+
)
|
| 203 |
|
| 204 |
if __name__ == "__main__":
|
| 205 |
demo.launch()
|