terry / app.py
ogegadavis254's picture
Update app.py
866f7a8 verified
raw
history blame
12.5 kB
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
import random
from datetime import datetime, timedelta
# 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;
}
</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 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 geographic usage data
def generate_geographic_data(technologies, regions):
geo_data = {}
for region in regions:
geo_data[region] = {}
for tech in technologies:
geo_data[region][tech] = random.uniform(0, 100)
return geo_data
# 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."
)
try:
stages = [
"Analyzing digital technologies...",
"Checking location data...",
"Running simulations...",
"Processing data...",
"Assessing impacts...",
"Calculating predictions...",
"Compiling results...",
"Finalizing analysis...",
"Preparing output..."
]
with st.spinner("Analyzing digital technologies and generating analysis..."):
for stage in stages:
st.spinner(stage)
time.sleep(2)
response = call_ai_model(all_message)
analysis_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:
analysis_text += delta["content"]
except json.JSONDecodeError:
continue
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.strip())
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)
geo_data = generate_geographic_data(digital_technologies, regions)
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)
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)
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)
st.markdown('</div>', unsafe_allow_html=True)
# Geographic Component
st.markdown('<div class="section">', unsafe_allow_html=True)
st.subheader("Geographic Distribution of Technology Usage")
fig_geo = px.choropleth(
locations=regions,
locationmode="country names",
color=[sum(geo_data[region].values()) for region in regions],
hover_name=regions,
color_continuous_scale=px.colors.sequential.Viridis,
title="Technology Usage Intensity Across Kenya"
)
fig_geo.update_geos(fitbounds="locations", visible=False)
st.plotly_chart(fig_geo)
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)
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">Powered by Together AI and Streamlit</div>', unsafe_allow_html=True)