ogegadavis254 commited on
Commit
866f7a8
1 Parent(s): a257648

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -32
app.py CHANGED
@@ -4,7 +4,10 @@ import os
4
  import json
5
  import pandas as pd
6
  import plotly.graph_objects as go
 
7
  import time
 
 
8
 
9
  # Custom CSS for styling
10
  st.markdown("""
@@ -67,10 +70,57 @@ def call_ai_model(all_message):
67
  }
68
 
69
  response = requests.post(url, json=payload, headers=headers, stream=True)
70
- response.raise_for_status() # Ensure HTTP request was successful
71
 
72
  return response
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  # Streamlit app layout
75
  st.markdown('<div class="header">Digital Technologies, Kinship, and Gender in Kenya</div>', unsafe_allow_html=True)
76
  st.markdown('<div class="subheader">Analyze and visualize the impact of digital technologies on kinship and gender dynamics in Kenya.</div>', unsafe_allow_html=True)
@@ -83,8 +133,8 @@ with st.container():
83
  issues = st.multiselect("Select issues of concern:", ["Trust", "Mistrust", "Data Privacy", "Fraud", "Social Classification"])
84
 
85
  st.subheader("Kenya-Specific Inputs")
86
- region = st.text_input("Enter region in Kenya:")
87
- gender_focus = st.multiselect("Select gender focus:", ["Male", "Female", "Non-binary", "All"])
88
  st.markdown('</div>', unsafe_allow_html=True)
89
 
90
  # Button to generate analysis
@@ -93,9 +143,9 @@ if st.button("Generate Analysis"):
93
  f"Analyze the impact of digital technologies on kinship and gender dynamics in Kenya. "
94
  f"Digital technologies: {', '.join(digital_technologies)}. "
95
  f"Issues of concern: {', '.join(issues)}. "
96
- f"Region: {region}. Gender focus: {', '.join(gender_focus)}. "
97
  f"Provide a detailed analysis of how these technologies impact family ties, trust, and gender roles. "
98
- f"Include specific impacts for each digital technology and issue.. "
99
  f"Organize the information in tables with the following columns: Digital Technology, Impact on Kinship, Impact on Gender Dynamics, Trust Issues. "
100
  f"Be as accurate and specific to Kenya as possible in your analysis. Make the response short and precise."
101
  )
@@ -114,7 +164,6 @@ if st.button("Generate Analysis"):
114
  ]
115
 
116
  with st.spinner("Analyzing digital technologies and generating analysis..."):
117
- # Loop through each stage, updating the spinner text and waiting for 2 seconds
118
  for stage in stages:
119
  st.spinner(stage)
120
  time.sleep(2)
@@ -126,7 +175,7 @@ if st.button("Generate Analysis"):
126
  if line:
127
  line_content = line.decode('utf-8')
128
  if line_content.startswith("data: "):
129
- line_content = line_content[6:] # Strip "data: " prefix
130
  try:
131
  json_data = json.loads(line_content)
132
  if "choices" in json_data:
@@ -137,45 +186,107 @@ if st.button("Generate Analysis"):
137
  continue
138
 
139
  st.success("Analysis completed!")
 
140
  # Display analysis
141
  st.markdown('<div class="section">', unsafe_allow_html=True)
142
  st.subheader("Digital Technologies Impact Analysis in Kenya")
143
  st.markdown(analysis_text.strip())
144
  st.markdown('</div>', unsafe_allow_html=True)
145
 
146
- # Prepare data for visualization
147
- results_data = {
148
- "Digital Technology": digital_technologies,
149
- "Issues of Concern": issues
150
- }
151
- results_df = pd.DataFrame(results_data)
152
 
153
- # Display results in a table
154
  st.markdown('<div class="section">', unsafe_allow_html=True)
155
- st.subheader("Digital Technologies Summary")
156
- st.table(results_df)
 
 
 
 
 
 
 
 
157
  st.markdown('</div>', unsafe_allow_html=True)
158
 
159
- # Create a radar chart for digital technology impacts
160
  st.markdown('<div class="section">', unsafe_allow_html=True)
161
- fig = go.Figure(data=go.Scatterpolar(
162
- r=[len(digital_technologies), len(issues)],
163
- theta=["Digital Technologies", "Issues of Concern"],
164
- fill='toself'
165
- ))
166
- fig.update_layout(
167
- polar=dict(
168
- radialaxis=dict(visible=True, range=[0, max(len(digital_technologies), len(issues))])
169
- ),
170
- showlegend=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  )
172
- st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  st.markdown('</div>', unsafe_allow_html=True)
174
 
175
- # Display raw analysis result for debugging
176
  st.markdown('<div class="section">', unsafe_allow_html=True)
177
- with st.expander("Show Raw Analysis"):
178
- st.text(analysis_text)
 
 
 
 
 
 
 
 
179
  st.markdown('</div>', unsafe_allow_html=True)
180
 
181
  except ValueError as ve:
@@ -186,4 +297,4 @@ if st.button("Generate Analysis"):
186
  st.error(f"An unexpected error occurred: {e}")
187
 
188
  # Footer
189
- st.markdown('<div class="footer">Powered by Together AI and Streamlit</div>', unsafe_allow_html=True)
 
4
  import json
5
  import pandas as pd
6
  import plotly.graph_objects as go
7
+ import plotly.express as px
8
  import time
9
+ import random
10
+ from datetime import datetime, timedelta
11
 
12
  # Custom CSS for styling
13
  st.markdown("""
 
70
  }
71
 
72
  response = requests.post(url, json=payload, headers=headers, stream=True)
73
+ response.raise_for_status()
74
 
75
  return response
76
 
77
+ # Function to generate simulated trust scores
78
+ def generate_trust_scores(technologies, issues):
79
+ trust_scores = {}
80
+ for tech in technologies:
81
+ trust_scores[tech] = {}
82
+ for issue in issues:
83
+ trust_scores[tech][issue] = random.uniform(0, 1)
84
+ return trust_scores
85
+
86
+ # Function to generate simulated kinship impact scores
87
+ def generate_kinship_impact(technologies):
88
+ impact_scores = {}
89
+ kinship_aspects = ["Family Communication", "Intergenerational Relationships", "Cultural Traditions"]
90
+ for tech in technologies:
91
+ impact_scores[tech] = {}
92
+ for aspect in kinship_aspects:
93
+ impact_scores[tech][aspect] = random.uniform(-1, 1)
94
+ return impact_scores
95
+
96
+ # Function to generate simulated gender impact scores
97
+ def generate_gender_impact(technologies, genders):
98
+ impact_scores = {}
99
+ for tech in technologies:
100
+ impact_scores[tech] = {}
101
+ for gender in genders:
102
+ impact_scores[tech][gender] = random.uniform(-1, 1)
103
+ return impact_scores
104
+
105
+ # Function to generate simulated geographic usage data
106
+ def generate_geographic_data(technologies, regions):
107
+ geo_data = {}
108
+ for region in regions:
109
+ geo_data[region] = {}
110
+ for tech in technologies:
111
+ geo_data[region][tech] = random.uniform(0, 100)
112
+ return geo_data
113
+
114
+ # Function to generate simulated long-term economic impact
115
+ def generate_economic_impact(technologies):
116
+ impact_data = {}
117
+ indicators = ["GDP Growth", "Employment Rate", "Digital Literacy"]
118
+ for tech in technologies:
119
+ impact_data[tech] = {}
120
+ for indicator in indicators:
121
+ impact_data[tech][indicator] = [random.uniform(-2, 5) for _ in range(5)] # 5-year projection
122
+ return impact_data
123
+
124
  # Streamlit app layout
125
  st.markdown('<div class="header">Digital Technologies, Kinship, and Gender in Kenya</div>', unsafe_allow_html=True)
126
  st.markdown('<div class="subheader">Analyze and visualize the impact of digital technologies on kinship and gender dynamics in Kenya.</div>', unsafe_allow_html=True)
 
133
  issues = st.multiselect("Select issues of concern:", ["Trust", "Mistrust", "Data Privacy", "Fraud", "Social Classification"])
134
 
135
  st.subheader("Kenya-Specific Inputs")
136
+ regions = st.multiselect("Select regions in Kenya:", ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"])
137
+ gender_focus = st.multiselect("Select gender focus:", ["Male", "Female", "Non-binary"])
138
  st.markdown('</div>', unsafe_allow_html=True)
139
 
140
  # Button to generate analysis
 
143
  f"Analyze the impact of digital technologies on kinship and gender dynamics in Kenya. "
144
  f"Digital technologies: {', '.join(digital_technologies)}. "
145
  f"Issues of concern: {', '.join(issues)}. "
146
+ f"Regions: {', '.join(regions)}. Gender focus: {', '.join(gender_focus)}. "
147
  f"Provide a detailed analysis of how these technologies impact family ties, trust, and gender roles. "
148
+ f"Include specific impacts for each digital technology and issue. "
149
  f"Organize the information in tables with the following columns: Digital Technology, Impact on Kinship, Impact on Gender Dynamics, Trust Issues. "
150
  f"Be as accurate and specific to Kenya as possible in your analysis. Make the response short and precise."
151
  )
 
164
  ]
165
 
166
  with st.spinner("Analyzing digital technologies and generating analysis..."):
 
167
  for stage in stages:
168
  st.spinner(stage)
169
  time.sleep(2)
 
175
  if line:
176
  line_content = line.decode('utf-8')
177
  if line_content.startswith("data: "):
178
+ line_content = line_content[6:]
179
  try:
180
  json_data = json.loads(line_content)
181
  if "choices" in json_data:
 
186
  continue
187
 
188
  st.success("Analysis completed!")
189
+
190
  # Display analysis
191
  st.markdown('<div class="section">', unsafe_allow_html=True)
192
  st.subheader("Digital Technologies Impact Analysis in Kenya")
193
  st.markdown(analysis_text.strip())
194
  st.markdown('</div>', unsafe_allow_html=True)
195
 
196
+ # Generate simulated data
197
+ trust_scores = generate_trust_scores(digital_technologies, issues)
198
+ kinship_impact = generate_kinship_impact(digital_technologies)
199
+ gender_impact = generate_gender_impact(digital_technologies, gender_focus)
200
+ geo_data = generate_geographic_data(digital_technologies, regions)
201
+ economic_impact = generate_economic_impact(digital_technologies)
202
 
203
+ # Trust and Fraud Metrics Visualization
204
  st.markdown('<div class="section">', unsafe_allow_html=True)
205
+ st.subheader("Trust and Fraud Metrics")
206
+ fig_trust = go.Figure()
207
+ for tech in digital_technologies:
208
+ fig_trust.add_trace(go.Bar(
209
+ x=list(trust_scores[tech].keys()),
210
+ y=list(trust_scores[tech].values()),
211
+ name=tech
212
+ ))
213
+ fig_trust.update_layout(barmode='group', title="Trust Scores by Technology and Issue")
214
+ st.plotly_chart(fig_trust)
215
  st.markdown('</div>', unsafe_allow_html=True)
216
 
217
+ # Kinship Structure Analysis
218
  st.markdown('<div class="section">', unsafe_allow_html=True)
219
+ st.subheader("Impact on Kinship Structures")
220
+ fig_kinship = go.Figure()
221
+ for tech in digital_technologies:
222
+ fig_kinship.add_trace(go.Scatterpolar(
223
+ r=list(kinship_impact[tech].values()),
224
+ theta=list(kinship_impact[tech].keys()),
225
+ fill='toself',
226
+ name=tech
227
+ ))
228
+ fig_kinship.update_layout(polar=dict(radialaxis=dict(visible=True, range=[-1, 1])), showlegend=True)
229
+ st.plotly_chart(fig_kinship)
230
+ st.markdown('</div>', unsafe_allow_html=True)
231
+
232
+ # Gender Impact Visualization
233
+ st.markdown('<div class="section">', unsafe_allow_html=True)
234
+ st.subheader("Gender Impact Analysis")
235
+ fig_gender = go.Figure()
236
+ for tech in digital_technologies:
237
+ fig_gender.add_trace(go.Bar(
238
+ x=list(gender_impact[tech].keys()),
239
+ y=list(gender_impact[tech].values()),
240
+ name=tech
241
+ ))
242
+ fig_gender.update_layout(barmode='group', title="Gender Impact by Technology")
243
+ st.plotly_chart(fig_gender)
244
+ st.markdown('</div>', unsafe_allow_html=True)
245
+
246
+ # Geographic Component
247
+ st.markdown('<div class="section">', unsafe_allow_html=True)
248
+ st.subheader("Geographic Distribution of Technology Usage")
249
+ fig_geo = px.choropleth(
250
+ locations=regions,
251
+ locationmode="country names",
252
+ color=[sum(geo_data[region].values()) for region in regions],
253
+ hover_name=regions,
254
+ color_continuous_scale=px.colors.sequential.Viridis,
255
+ title="Technology Usage Intensity Across Kenya"
256
  )
257
+ fig_geo.update_geos(fitbounds="locations", visible=False)
258
+ st.plotly_chart(fig_geo)
259
+ st.markdown('</div>', unsafe_allow_html=True)
260
+
261
+ # Long-term Economic Impact
262
+ st.markdown('<div class="section">', unsafe_allow_html=True)
263
+ st.subheader("Projected Long-term Economic Impact")
264
+ fig_economic = go.Figure()
265
+ years = [datetime.now().year + i for i in range(5)]
266
+ for tech in digital_technologies:
267
+ for indicator in economic_impact[tech]:
268
+ fig_economic.add_trace(go.Scatter(
269
+ x=years,
270
+ y=economic_impact[tech][indicator],
271
+ mode='lines+markers',
272
+ name=f"{tech} - {indicator}"
273
+ ))
274
+ fig_economic.update_layout(title="5-Year Economic Impact Projection", xaxis_title="Year", yaxis_title="Impact (%)")
275
+ st.plotly_chart(fig_economic)
276
  st.markdown('</div>', unsafe_allow_html=True)
277
 
278
+ # Ethical Considerations
279
  st.markdown('<div class="section">', unsafe_allow_html=True)
280
+ st.subheader("Ethical Considerations")
281
+ ethical_concerns = [
282
+ "Data Privacy: Ensuring user data is protected and used responsibly.",
283
+ "Digital Divide: Addressing inequality in access to digital technologies.",
284
+ "Cultural Preservation: Balancing technological advancement with traditional values.",
285
+ "Algorithmic Bias: Mitigating biases in AI and machine learning systems.",
286
+ "Cybersecurity: Protecting users from fraud and cyber attacks."
287
+ ]
288
+ for concern in ethical_concerns:
289
+ st.write(f"• {concern}")
290
  st.markdown('</div>', unsafe_allow_html=True)
291
 
292
  except ValueError as ve:
 
297
  st.error(f"An unexpected error occurred: {e}")
298
 
299
  # Footer
300
+ st.markdown('<div class="footer">Powered by Together AI and Streamlit</div>', unsafe_allow_html=True)