File size: 12,846 Bytes
9f54a3b
71ec4a8
9f54a3b
0e00146
a645649
c50f71f
866f7a8
9d150a9
866f7a8
c7e3a36
a9c7401
91d2c85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7e3a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2c85
 
 
7f8c6d6
 
71ec4a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866f7a8
71ec4a8
8092b5a
71ec4a8
c7e3a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866f7a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fcff87
91d2c85
 
7fcff87
91d2c85
 
 
 
 
 
7fcff87
91d2c85
866f7a8
 
91d2c85
a645649
91d2c85
7f8c6d6
0957448
7f8c6d6
 
 
866f7a8
7f8c6d6
866f7a8
7f8c6d6
e7448c6
0957448
7fcff87
9104631
65e9088
7f8c6d6
65e9088
7f8c6d6
 
65e9088
 
 
 
 
45b3e7d
c7e3a36
 
9ad5122
c7e3a36
 
 
 
 
 
 
a645649
c7e3a36
 
 
 
 
 
 
a645649
c7e3a36
 
 
 
 
866f7a8
c7e3a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866f7a8
c7e3a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866f7a8
c7e3a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad5122
c7e3a36
 
 
 
 
 
 
 
 
 
 
 
 
65eab1d
71ec4a8
 
 
 
 
9104631
91d2c85
 
e7448c6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import streamlit as st
import requests
import os
import json
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import time
from datetime import datetime, timedelta
import random

# Custom CSS for styling
st.markdown("""
    <style>
        .stApp {
            background: #f5f5f5;
        }
        .header {
            font-size: 36px;
            font-weight: bold;
            color: #4CAF50;
            text-align: center;
            margin-bottom: 20px;
        }
        .subheader {
            font-size: 24px;
            font-weight: bold;
            color: #4CAF50;
            text-align: center;
            margin-bottom: 20px;
        }
        .section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .footer {
            text-align: center;
            font-size: 14px;
            color: #777;
            margin-top: 20px;
        }
        .stProgress > div > div > div > div {
            background-image: linear-gradient(to right, #4CAF50, #45a049);
        }
        @keyframes gradient {
            0% {background-position: 0% 50%;}
            50% {background-position: 100% 50%;}
            100% {background-position: 0% 50%;}
        }
        .animated-div {
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradient 15s ease infinite;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 10px;
        }
    </style>
""", unsafe_allow_html=True)

# Function to call the Together AI model
def call_ai_model(all_message):
    url = "https://api.together.xyz/v1/chat/completions"
    payload = {
        "model": "NousResearch/Nous-Hermes-2-Yi-34B",
        "temperature": 1.05,
        "top_p": 0.9,
        "top_k": 50,
        "repetition_penalty": 1,
        "n": 1,
        "messages": [{"role": "user", "content": all_message}],
        "stream_tokens": True,
    }

    TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
    if TOGETHER_API_KEY is None:
        raise ValueError("TOGETHER_API_KEY environment variable not set.")
    
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "Authorization": f"Bearer {TOGETHER_API_KEY}",
    }

    response = requests.post(url, json=payload, headers=headers, stream=True)
    response.raise_for_status()

    return response

# Function to process AI response
def process_ai_response(response):
    explanation_text = ""
    for line in response.iter_lines():
        if line:
            line_content = line.decode('utf-8')
            if line_content.startswith("data: "):
                line_content = line_content[6:]
            try:
                json_data = json.loads(line_content)
                if "choices" in json_data:
                    delta = json_data["choices"][0]["delta"]
                    if "content" in delta:
                        explanation_text += delta["content"]
            except json.JSONDecodeError:
                continue
    return explanation_text.strip()

# Function to get AI explanation for graphs
def get_ai_explanation(graph_type, data):
    explanation_prompt = f"Provide a short, clear explanation of the following {graph_type} graph data: {data}"
    response = call_ai_model(explanation_prompt)
    explanation = process_ai_response(response)
    return explanation

# Function to generate simulated trust scores
def generate_trust_scores(technologies, issues):
    trust_scores = {}
    for tech in technologies:
        trust_scores[tech] = {}
        for issue in issues:
            trust_scores[tech][issue] = random.uniform(0, 1)
    return trust_scores

# Function to generate simulated kinship impact scores
def generate_kinship_impact(technologies):
    impact_scores = {}
    kinship_aspects = ["Family Communication", "Intergenerational Relationships", "Cultural Traditions"]
    for tech in technologies:
        impact_scores[tech] = {}
        for aspect in kinship_aspects:
            impact_scores[tech][aspect] = random.uniform(-1, 1)
    return impact_scores

# Function to generate simulated gender impact scores
def generate_gender_impact(technologies, genders):
    impact_scores = {}
    for tech in technologies:
        impact_scores[tech] = {}
        for gender in genders:
            impact_scores[tech][gender] = random.uniform(-1, 1)
    return impact_scores

# Function to generate simulated long-term economic impact
def generate_economic_impact(technologies):
    impact_data = {}
    indicators = ["GDP Growth", "Employment Rate", "Digital Literacy"]
    for tech in technologies:
        impact_data[tech] = {}
        for indicator in indicators:
            impact_data[tech][indicator] = [random.uniform(-2, 5) for _ in range(5)]  # 5-year projection
    return impact_data

# Streamlit app layout
st.markdown('<div class="header">Digital Technologies, Kinship, and Gender in Kenya</div>', unsafe_allow_html=True)
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)

# Input section
with st.container():
    st.markdown('<div class="section">', unsafe_allow_html=True)
    st.subheader("Digital Technology Impacts")
    digital_technologies = st.multiselect("Select digital technologies:", ["Big Data Analytics", "Biometric Authentication", "Blockchain", "E-commerce", "Social Media Platforms"])
    issues = st.multiselect("Select issues of concern:", ["Trust", "Mistrust", "Data Privacy", "Fraud", "Social Classification"])

    st.subheader("Kenya-Specific Inputs")
    regions = st.multiselect("Select regions in Kenya:", ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"])
    gender_focus = st.multiselect("Select gender focus:", ["Male", "Female", "Non-binary"])
    st.markdown('</div>', unsafe_allow_html=True)

# Button to generate analysis
if st.button("Generate Analysis"):
    all_message = (
        f"Analyze the impact of digital technologies on kinship and gender dynamics in Kenya. "
        f"Digital technologies: {', '.join(digital_technologies)}. "
        f"Issues of concern: {', '.join(issues)}. "
        f"Regions: {', '.join(regions)}. Gender focus: {', '.join(gender_focus)}. "
        f"Provide a detailed analysis of how these technologies impact family ties, trust, and gender roles. "
        f"Include specific impacts for each digital technology and issue. "
        f"Organize the information in tables with the following columns: Digital Technology, Impact on Kinship, Impact on Gender Dynamics, Trust Issues. "
        f"Be as accurate and specific to Kenya as possible in your analysis. Make the response short and precise. Do not give anything like a conclusion after generating"
    )

    try:
        stages = [
            "Analyzing digital technologies...",
            "Running simulations...",
            "Processing data...",
            "Assessing impacts...",
            "Calculating predictions...",
            "Compiling results...",
            "Finalizing analysis...",
            "Preparing output..."
        ]
        
        progress_bar = st.progress(0)
        status_text = st.empty()

        for i, stage in enumerate(stages):
            status_text.markdown(f'<div class="animated-div">{stage}</div>', unsafe_allow_html=True)
            progress_bar.progress((i + 1) / len(stages))
            time.sleep(1)
        
        response = call_ai_model(all_message)
        analysis_text = process_ai_response(response)

        st.success("Analysis completed!")
        
        # Display analysis
        st.markdown('<div class="section">', unsafe_allow_html=True)
        st.subheader("Digital Technologies Impact Analysis in Kenya")
        st.markdown(analysis_text)
        st.markdown('</div>', unsafe_allow_html=True)

        # Generate simulated data
        trust_scores = generate_trust_scores(digital_technologies, issues)
        kinship_impact = generate_kinship_impact(digital_technologies)
        gender_impact = generate_gender_impact(digital_technologies, gender_focus)
        economic_impact = generate_economic_impact(digital_technologies)

        # Trust and Fraud Metrics Visualization
        st.markdown('<div class="section">', unsafe_allow_html=True)
        st.subheader("Trust and Fraud Metrics")
        fig_trust = go.Figure()
        for tech in digital_technologies:
            fig_trust.add_trace(go.Bar(
                x=list(trust_scores[tech].keys()),
                y=list(trust_scores[tech].values()),
                name=tech
            ))
        fig_trust.update_layout(barmode='group', title="Trust Scores by Technology and Issue")
        st.plotly_chart(fig_trust)
        trust_explanation = get_ai_explanation("Trust and Fraud Metrics", trust_scores)
        st.markdown(f"**AI Explanation:** {trust_explanation}")
        st.markdown('</div>', unsafe_allow_html=True)

        # Kinship Structure Analysis
        st.markdown('<div class="section">', unsafe_allow_html=True)
        st.subheader("Impact on Kinship Structures")
        fig_kinship = go.Figure()
        for tech in digital_technologies:
            fig_kinship.add_trace(go.Scatterpolar(
                r=list(kinship_impact[tech].values()),
                theta=list(kinship_impact[tech].keys()),
                fill='toself',
                name=tech
            ))
        fig_kinship.update_layout(polar=dict(radialaxis=dict(visible=True, range=[-1, 1])), showlegend=True)
        st.plotly_chart(fig_kinship)
        kinship_explanation = get_ai_explanation("Impact on Kinship Structures", kinship_impact)
        st.markdown(f"**AI Explanation:** {kinship_explanation}")
        st.markdown('</div>', unsafe_allow_html=True)

        # Gender Impact Visualization
        st.markdown('<div class="section">', unsafe_allow_html=True)
        st.subheader("Gender Impact Analysis")
        fig_gender = go.Figure()
        for tech in digital_technologies:
            fig_gender.add_trace(go.Bar(
                x=list(gender_impact[tech].keys()),
                y=list(gender_impact[tech].values()),
                name=tech
            ))
        fig_gender.update_layout(barmode='group', title="Gender Impact by Technology")
        st.plotly_chart(fig_gender)
        gender_explanation = get_ai_explanation("Gender Impact Analysis", gender_impact)
        st.markdown(f"**AI Explanation:** {gender_explanation}")
        st.markdown('</div>', unsafe_allow_html=True)

        # Long-term Economic Impact
        st.markdown('<div class="section">', unsafe_allow_html=True)
        st.subheader("Projected Long-term Economic Impact")
        fig_economic = go.Figure()
        years = [datetime.now().year + i for i in range(5)]
        for tech in digital_technologies:
            for indicator in economic_impact[tech]:
                fig_economic.add_trace(go.Scatter(
                    x=years,
                    y=economic_impact[tech][indicator],
                    mode='lines+markers',
                    name=f"{tech} - {indicator}"
                ))
        fig_economic.update_layout(title="5-Year Economic Impact Projection", xaxis_title="Year", yaxis_title="Impact (%)")
        st.plotly_chart(fig_economic)
        economic_explanation = get_ai_explanation("Projected Long-term Economic Impact", economic_impact)
        st.markdown(f"**AI Explanation:** {economic_explanation}")
        st.markdown('</div>', unsafe_allow_html=True)

        # Ethical Considerations
        st.markdown('<div class="section">', unsafe_allow_html=True)
        st.subheader("Ethical Considerations")
        ethical_concerns = [
            "Data Privacy: Ensuring user data is protected and used responsibly.",
            "Digital Divide: Addressing inequality in access to digital technologies.",
            "Cultural Preservation: Balancing technological advancement with traditional values.",
            "Algorithmic Bias: Mitigating biases in AI and machine learning systems.",
            "Cybersecurity: Protecting users from fraud and cyber attacks"
        ]
        for concern in ethical_concerns:
            st.write(f"• {concern}")
        st.markdown('</div>', unsafe_allow_html=True)

    except ValueError as ve:
        st.error(f"Configuration error: {ve}")
    except requests.exceptions.RequestException as re:
        st.error(f"Request error: {re}")
    except Exception as e:
        st.error(f"An unexpected error occurred: {e}")

# Footer
st.markdown('<div class="footer">Developed by TERESA ABUYA</div>', unsafe_allow_html=True)