LeonceNsh commited on
Commit
6516df7
·
verified ·
1 Parent(s): 3cb17f6

Update gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +49 -43
gradio_app.py CHANGED
@@ -1,8 +1,8 @@
1
  import gradio as gr
2
- import requests
3
  import pandas as pd
4
  import plotly.express as px
5
  import plotly.graph_objects as go
 
6
 
7
  # Color palette for accessibility
8
  colorblind_palette = [
@@ -14,38 +14,36 @@ colorblind_palette = [
14
 
15
  # Cache for data (simple in-memory cache)
16
  _cached_data = None
17
- _cache_timestamp = None
18
 
19
  def get_detention_data():
20
  """
21
- Get the data which powers TRAC's "ICE Detainees" page and return it as a dataframe.
22
  """
23
- global _cached_data, _cache_timestamp
24
 
25
- import time
26
- current_time = time.time()
27
-
28
- # Check if we have cached data that's less than 15 minutes old
29
- if _cached_data is not None and _cache_timestamp is not None:
30
- if current_time - _cache_timestamp < 900: # 15 minutes in seconds
31
- return _cached_data
32
 
33
  try:
34
- response = requests.get(
35
- "https://tracreports.org/immigration/detentionstats/pop_agen_table.json"
36
- )
37
- response.raise_for_status()
 
 
38
 
39
- df = pd.DataFrame(response.json())
40
- df.date = pd.to_datetime(df.date).dt.date
 
41
 
42
  # Cache the data
43
  _cached_data = df
44
- _cache_timestamp = current_time
45
 
46
  return df
47
  except Exception as e:
48
- # Return empty dataframe if request fails
 
49
  return pd.DataFrame()
50
 
51
  def get_col_prefix(authority):
@@ -245,7 +243,14 @@ def update_chart(dataset, display, authority):
245
 
246
  def get_data_info():
247
  """Get information about the data."""
248
- return """"""
 
 
 
 
 
 
 
249
 
250
  def download_data():
251
  """Prepare data for download."""
@@ -254,10 +259,18 @@ def download_data():
254
  return None
255
  return df.to_csv(index=False)
256
 
 
 
 
 
 
 
 
257
  # Create the Gradio interface
258
  def create_app():
259
  with gr.Blocks(title="US Immigration Enforcement Data", theme=gr.themes.Soft()) as app:
260
  gr.Markdown("# US Immigration Enforcement Data")
 
261
 
262
  with gr.Tabs():
263
  with gr.TabItem("Graphs"):
@@ -307,33 +320,26 @@ def create_app():
307
  outputs=[chart, footnote]
308
  )
309
 
310
- with gr.TabItem("Data"):
311
- gr.Markdown(get_data_info())
312
 
313
- with gr.Row():
314
- refresh_btn = gr.Button("Refresh Data")
315
- download_btn = gr.DownloadButton(
316
- "Download as CSV",
317
- lambda: download_data(),
318
- filename="ice_detention_data.csv"
319
- )
320
-
321
- data_display = gr.Dataframe(
322
- label="ICE Detention Data",
323
- wrap=True
324
- )
325
 
326
- def refresh_data():
327
- global _cached_data, _cache_timestamp
328
- _cached_data = None
329
- _cache_timestamp = None
330
- df = get_detention_data()
331
- return df
332
 
333
- refresh_btn.click(refresh_data, outputs=[data_display])
334
 
335
- # Load data on app start
336
- app.load(lambda: get_detention_data(), outputs=[data_display])
337
 
338
  return app
339
 
 
1
  import gradio as gr
 
2
  import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
+ import json
6
 
7
  # Color palette for accessibility
8
  colorblind_palette = [
 
14
 
15
  # Cache for data (simple in-memory cache)
16
  _cached_data = None
 
17
 
18
  def get_detention_data():
19
  """
20
+ Load the pre-downloaded detention data from CSV file and return it as a dataframe.
21
  """
22
+ global _cached_data
23
 
24
+ # Return cached data if available
25
+ if _cached_data is not None:
26
+ return _cached_data
 
 
 
 
27
 
28
  try:
29
+ # Read the file as text first since it contains JSON
30
+ with open('ice_detention_data.csv', 'r') as file:
31
+ json_data = file.read().strip()
32
+
33
+ # Parse the JSON data
34
+ data = json.loads(json_data)
35
 
36
+ # Convert to DataFrame
37
+ df = pd.DataFrame(data)
38
+ df['date'] = pd.to_datetime(df['date']).dt.date
39
 
40
  # Cache the data
41
  _cached_data = df
 
42
 
43
  return df
44
  except Exception as e:
45
+ print(f"Error loading data: {e}")
46
+ # Return empty dataframe if file loading fails
47
  return pd.DataFrame()
48
 
49
  def get_col_prefix(authority):
 
243
 
244
  def get_data_info():
245
  """Get information about the data."""
246
+ return """**Data Source:** TRAC Immigration Reports
247
+
248
+ This dataset contains ICE detention statistics including:
249
+ - Total detainees by arresting authority (ICE vs CBP)
250
+ - Criminal status breakdown (Convicted, Pending charges, Other immigration violators)
251
+ - Historical data from May 2019 to July 2025
252
+
253
+ The data is sourced from TRAC's ICE Detainees page and represents the most recent snapshot of detention statistics."""
254
 
255
  def download_data():
256
  """Prepare data for download."""
 
259
  return None
260
  return df.to_csv(index=False)
261
 
262
+ def refresh_data():
263
+ """Clear cache and reload data."""
264
+ global _cached_data
265
+ _cached_data = None
266
+ df = get_detention_data()
267
+ return df
268
+
269
  # Create the Gradio interface
270
  def create_app():
271
  with gr.Blocks(title="US Immigration Enforcement Data", theme=gr.themes.Soft()) as app:
272
  gr.Markdown("# US Immigration Enforcement Data")
273
+ gr.Markdown("*Interactive visualization of ICE detention statistics*")
274
 
275
  with gr.Tabs():
276
  with gr.TabItem("Graphs"):
 
320
  outputs=[chart, footnote]
321
  )
322
 
323
+ # with gr.TabItem("Data"):
324
+ # gr.Markdown(get_data_info())
325
 
326
+ # with gr.Row():
327
+ # refresh_btn = gr.Button("Refresh Data")
328
+ # download_btn = gr.DownloadButton(
329
+ # "Download as CSV",
330
+ # lambda: download_data() #,
331
+ # #filename="ice_detention_data.csv"
332
+ # )
 
 
 
 
 
333
 
334
+ # data_display = gr.Dataframe(
335
+ # label="ICE Detention Data",
336
+ # wrap=True
337
+ # )
 
 
338
 
339
+ # refresh_btn.click(refresh_data, outputs=[data_display])
340
 
341
+ # # Load data on app start
342
+ # app.load(lambda: get_detention_data(), outputs=[data_display])
343
 
344
  return app
345