dotoking commited on
Commit
823c94e
·
verified ·
1 Parent(s): a7fedd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -49
app.py CHANGED
@@ -1,49 +1,101 @@
1
- # app.py (Simplified Gradio code)
2
-
3
- import gradio as gr
4
- from cear_model import CEARModel
5
- import pandas as pd
6
- # ... (include logic to load PLATFORM_WEIGHTS)
7
-
8
- # Instantiate the model globally
9
- cear_analyzer = CEARModel()
10
-
11
- def analyze_user_data(input_table):
12
- # 1. Convert Gradio input (list of lists) to DataFrame
13
- user_data_df = pd.DataFrame(input_table, columns=['platform_name', 'minutes_per_week'])
14
- user_data_df['minutes_per_week'] = pd.to_numeric(user_data_df['minutes_per_week'], errors='coerce').fillna(0)
15
-
16
- # 2. Call the core model
17
- raw_scores = cear_analyzer.calculate_scores(user_data_df)
18
-
19
- # 3. Format output for the user (The "App" layer)
20
- summary = f"""
21
- ## 📊 Analysis Summary
22
- - **Cultural Connectedness Score (C-Score):** **{raw_scores['C_Score']:.2f}**
23
- - **Algorithmic Risk Score (A-Risk):** **{raw_scores['A_Risk']:.2f}**
24
- - **Platform Diversity Index (D-Index):** **{raw_scores['D_Index']:.2f}**
25
- ---
26
- ### 📝 Interpretation
27
- *Your C-Score is based on logarithmically scaled time, reflecting diminishing returns. Your A-Risk is based on raw time, reflecting concentrated attention.*
28
- """
29
-
30
- # Return the formatted string and potentially a table of efficiency
31
- return summary, pd.DataFrame(raw_scores['Per_Platform_Efficiency'])
32
-
33
- # Define the Gradio interface
34
- iface = gr.Interface(
35
- fn=analyze_user_data,
36
- inputs=gr.Dataframe(
37
- headers=['platform_name', 'minutes_per_week'],
38
- row_count=5,
39
- col_count=(2, 'fixed'),
40
- label="Weekly Screen Time Input (Source data from OS Tracker)"
41
- ),
42
- outputs=[
43
- gr.Markdown(label="Score Results"),
44
- gr.Dataframe(label="Per-Platform Cultural Efficiency")
45
- ],
46
- title="CEAR Baseline: Cultural Exposure & Algorithmic Risk Analyzer"
47
- )
48
-
49
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from cear_model import CEARModel
3
+ import pandas as pd
4
+
5
+ # Instantiate the model globally
6
+ cear_analyzer = CEARModel()
7
+
8
+ # --- Configuration: Default Values for Pre-population ---
9
+ # Users will see these rows filled in when the app loads
10
+ DEFAULT_DATA = [
11
+ ["TikTok", 0],
12
+ ["Instagram", 0],
13
+ ["YouTube", 0],
14
+ ["X/Twitter", 0],
15
+ ["Reddit", 0],
16
+ ["Facebook", 0],
17
+ ["LinkedIn", 0]
18
+ ]
19
+
20
+ def analyze_user_data(input_table, variety_rating, fomo_rating):
21
+ """
22
+ Analyzes screen time + subjective survey data.
23
+ """
24
+ # 1. Convert Gradio input to DataFrame
25
+ user_data_df = pd.DataFrame(input_table, columns=['platform_name', 'minutes_per_week'])
26
+
27
+ # Clean inputs: coerce non-numbers to 0
28
+ user_data_df['minutes_per_week'] = pd.to_numeric(user_data_df['minutes_per_week'], errors='coerce').fillna(0)
29
+
30
+ # 2. Call the core model
31
+ raw_scores = cear_analyzer.calculate_scores(user_data_df)
32
+
33
+ # 3. Generate Analysis Summary
34
+ # We now integrate the survey scores into the interpretation
35
+
36
+ # Logic for simple feedback based on the new survey inputs
37
+ variety_status = "High" if variety_rating >= 4 else ("Low" if variety_rating <= 2 else "Moderate")
38
+ fomo_status = "High" if fomo_rating >= 4 else ("Low" if fomo_rating <= 2 else "Moderate")
39
+
40
+ summary = f"""
41
+ ## 📊 Analysis Summary
42
+
43
+ ### 🧠 Core Metrics
44
+ - **Cultural Connectedness Score (C-Score):** **{raw_scores['C_Score']:.2f}**
45
+ - **Algorithmic Risk Score (A-Risk):** **{raw_scores['A_Risk']:.2f}**
46
+ - **Platform Diversity Index (D-Index):** **{raw_scores['D_Index']:.2f}**
47
+
48
+ ### 🗣️ Self-Reported Context
49
+ - **Perceived Variety:** {variety_rating}/5 ({variety_status})
50
+ - **FOMO Intensity:** {fomo_rating}/5 ({fomo_status})
51
+
52
+ ---
53
+ ### 📝 Interpretation
54
+ *Your C-Score reflects exposure to viral trends based on logarithmically scaled time. Your A-Risk captures vulnerability to high-intensity feeds.*
55
+
56
+ **Insight:** You reported **{variety_status} variety** and **{fomo_status} FOMO**.
57
+ {'⚠️ High FOMO suggests you may be relying on these feeds for social validation despite the algorithmic risk.' if fomo_status == 'High' else '✅ Low FOMO indicates a healthy detachment from the feed cycle.'}
58
+ """
59
+
60
+ # Return the summary text and the efficiency table
61
+ return summary, pd.DataFrame(raw_scores['Per_Platform_Efficiency'])
62
+
63
+ # --- Define the Gradio Interface ---
64
+ with gr.Blocks(title="CEAR Model") as demo:
65
+ gr.Markdown("# 🧭 Cultural Exposure & Algorithmic Risk (CEAR) Model")
66
+ gr.Markdown("Enter your weekly screen time (minutes) and rate your experience below.")
67
+
68
+ with gr.Row():
69
+ with gr.Column(scale=2):
70
+ # The Dataframe with pre-populated values
71
+ input_table = gr.Dataframe(
72
+ headers=['platform_name', 'minutes_per_week'],
73
+ value=DEFAULT_DATA, # <--- THIS PRE-POPULATES THE ROWS
74
+ datatype=["str", "number"],
75
+ row_count=7,
76
+ col_count=(2, 'fixed'),
77
+ label="Weekly Screen Time (Minutes)"
78
+ )
79
+
80
+ with gr.Column(scale=1):
81
+ # New Survey Questions
82
+ gr.Markdown("### 🧠 Self-Reflection")
83
+ variety_slider = gr.Slider(1, 5, step=1, value=3, label="How diverse does your feed feel? (1=Repetitive, 5=Diverse)")
84
+ fomo_slider = gr.Slider(1, 5, step=1, value=3, label="How strong is your FOMO? (1=None, 5=Intense)")
85
+
86
+ analyze_btn = gr.Button("Analyze My Risk", variant="primary")
87
+
88
+ with gr.Row():
89
+ output_text = gr.Markdown(label="Analysis Results")
90
+ output_table = gr.Dataframe(label="Cultural Efficiency (Score per Minute)")
91
+
92
+ # Connect the inputs to the function
93
+ analyze_btn.click(
94
+ fn=analyze_user_data,
95
+ inputs=[input_table, variety_slider, fomo_slider],
96
+ outputs=[output_text, output_table]
97
+ )
98
+
99
+ # Launch with the required server binding
100
+ if __name__ == "__main__":
101
+ demo.launch(server_name="0.0.0.0", server_port=7860)