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(""" """, 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('
Digital Technologies, Kinship, and Gender in Kenya
', unsafe_allow_html=True) st.markdown('
Analyze and visualize the impact of digital technologies on kinship and gender dynamics in Kenya.
', unsafe_allow_html=True) # Input section with st.container(): st.markdown('
', 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('
', 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'
{stage}
', 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('
', unsafe_allow_html=True) st.subheader("Digital Technologies Impact Analysis in Kenya") st.markdown(analysis_text) st.markdown('
', 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('
', 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('
', unsafe_allow_html=True) # Kinship Structure Analysis st.markdown('
', 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('
', unsafe_allow_html=True) # Gender Impact Visualization st.markdown('
', 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('
', unsafe_allow_html=True) # Long-term Economic Impact st.markdown('
', 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('
', unsafe_allow_html=True) # Ethical Considerations st.markdown('
', 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('
', 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('', unsafe_allow_html=True)