JAMBAZI / app.py
ANON-STUDIOS-254's picture
Update app.py
da15f41 verified
import gradio as gr
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from huggingface_hub import InferenceClient
# Initialize Hugging Face Inference Client
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Set default values for model parameters and system message
DEFAULT_MAX_TOKENS = 1000
DEFAULT_TEMPERATURE = 0.7
DEFAULT_TOP_P = 0.95
DEFAULT_SYSTEM_MESSAGE = "You are an expert in criminogenic risk prediction. Provide expert recommendations addressing the user directly."
DEFAULT_ALIAS = "anon" # Default alias
def calculate_criminogenic_risk(individual_score, social_family_score, environmental_score, alias=DEFAULT_ALIAS, max_tokens=DEFAULT_MAX_TOKENS, temperature=DEFAULT_TEMPERATURE, top_p=DEFAULT_TOP_P, system_message=DEFAULT_SYSTEM_MESSAGE):
# Calculate the criminogenic risk score as a percentage (0 to 100)
risk_score = ((individual_score + social_family_score + environmental_score) / 15) * 100
# Construct the input message for the model with context
message = (f"{system_message}\n"
f"On a scale of 1-5, with 5 being the highest risk and 1 being the lowest, {alias} rated the following:\n"
f"Individual Factors: {individual_score}\n"
f"Social and Family Factors: {social_family_score}\n"
f"Environmental and Socioeconomic Factors: {environmental_score}\n"
f"Please provide personalized recommendations for {alias}, addressing them directly.")
# Generate recommendations using the Hugging Face model
response = client.chat_completion(
[{"role": "user", "content": message}],
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p
)
recommendations = response.choices[0].message['content']
# Convert the recommendations to address the user in first person
recommendations = recommendations.replace("You should", "I recommend that you")
return risk_score, recommendations
def analyze_criminogenic_risk(individual_score, social_family_score, environmental_score, alias):
# Use default alias if none is provided
alias = alias or DEFAULT_ALIAS
# Calculate the criminogenic risk score and generate recommendations
risk_score, recommendations = calculate_criminogenic_risk(individual_score, social_family_score, environmental_score, alias)
# Create a bar graph to visualize the input scores
fig, ax = plt.subplots(figsize=(10, 6)) # Increased size for better visibility
categories = ["Individual Factors", "Social & Family Factors", "Environmental Factors"]
values = [individual_score, social_family_score, environmental_score]
bars = ax.bar(categories, values, color=['#FF6F61', '#6B5B95', '#88B04B']) # Distinct colors
# Improve graph display
ax.set_ylabel('Score (1-5)', fontsize=14, color='#333333')
ax.set_title(f'Criminogenic Risk Factors for {alias}', fontsize=16, color='#333333')
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.tick_params(axis='y', colors='#333333')
ax.tick_params(axis='x', colors='#333333')
# Add value labels on the bars
for bar in bars:
yval = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, yval, int(yval), va='bottom', ha='center', color='black', fontsize=12)
return fig, recommendations
# Custom CSS for Ukiyo-e theme
custom_css = """
body {
font-family: 'Garamond', serif;
background-color: #FAF3F3; /* Light background color */
}
.container {
border: 2px solid #FF6F61; /* Distinctive border color */
border-radius: 10px;
padding: 20px;
background-color: #FFFFFF; /* White background for content */
}
h1 {
color: #FF6F61; /* Matching title color */
}
h2, h3, h4 {
color: #333333; /* Dark grey for headings */
}
.gradio-slider .slider .slider-handle {
background-color: #88B04B; /* Slider handle color */
}
.gradio-slider .slider .slider-track {
background-color: #6B5B95; /* Slider track color */
}
.gradio-textbox input, .gradio-textbox textarea {
border: 2px solid #333333; /* Dark border for inputs */
}
.gradio-button {
background-color: #FFD700; /* Gold background for buttons */
color: #000000; /* Black text for buttons */
}
"""
# Create the Gradio interface with custom CSS
inputs = [
gr.Slider(minimum=1, maximum=5, step=1, label="How much do personal issues (like mental health or behavior) affect your risk? (1 = Not at all, 5 = Very much)"),
gr.Slider(minimum=1, maximum=5, step=1, label="How much do your family or social relationships affect your risk? (1 = Not at all, 5 = Very much)"),
gr.Slider(minimum=1, maximum=5, step=1, label="How much does your environment (like your neighborhood or economic situation) affect your risk? (1 = Not at all, 5 = Very much)"),
gr.Textbox(placeholder="Enter a single-word alias (e.g., anon).", label="Your Alias", lines=1)
]
outputs = [
gr.Plot(label="Criminogenic Risk Graph"),
gr.Textbox(label="Personalized Recommendations", lines=5)
]
gr.Interface(
fn=analyze_criminogenic_risk,
inputs=inputs,
outputs=outputs,
title="JAMBAZI: Criminogenic Risk Factors Predictor",
description="Evaluate how individual, social, and environmental factors influence your risk by rating each on a scale from 1 (Not at all) to 5 (Very much). Receive a risk score and personalized recommendations based on your inputs.",
css=custom_css # Apply custom CSS
).launch()