API Documentation
API Overview
TeenSmartInsight integrates with external APIs to enhance its functionality, primarily using the Google Gemini API for AI-powered analysis and recommendations. This document outlines the API integrations and how they are used within the application.
Google Gemini API Integration
Overview
The Google Gemini API is used to analyze user data and provide personalized recommendations based on technology usage patterns and addiction risk levels. The integration is implemented in the gemini_service.py file.
Authentication
The API requires an API key, which should be stored in the .env file:
GEMINI_API_KEY=your_api_key_here
Implementation
def analyze_prediction(self, user_data, prediction):
"""
Analyzes the user data and prediction using Gemini
Args:
user_data (dict): User input data
prediction: Result from the prediction model
Returns:
str: Analysis generated by Gemini
"""
# Create the model
model = genai.GenerativeModel('gemini-1.5-pro')
# Prepare the prompt
prompt = f"""
Analyze the following technology usage data for an adolescent and provide recommendations:
- Daily usage hours: {user_data['Daily_Usage_Hours']}
- Apps used daily: {user_data['Apps_Used_Daily']}
- Time on social media (hours): {user_data['Time_on_Social_Media']}
- Time on gaming (hours): {user_data['Time_on_Gaming']}
- Phone checks per day: {user_data['Phone_Checks_Per_Day']}
- Sleep hours: {user_data['Sleep_Hours']}
- Weekend usage hours: {user_data['Weekend_Usage_Hours']}
- Academic performance (scale 1-10): {user_data['Academic_Performance']}
The prediction model indicates an addiction level of: {prediction}
Please provide:
1. A brief analysis of the technology usage pattern
2. Specific recommendations for improving digital habits
3. Potential warning signs that should be addressed
"""
# Generate the response
response = model.generate_content(prompt)
# Convert Markdown to HTML
html_content = markdown2.markdown(response.text, extras=["tables", "fenced-code-blocks"])
return html_content
Error Handling
The service includes error handling to gracefully handle API failures:
- If the API key is not configured, it returns an appropriate message
- If the API call fails, it returns an error message
- The application falls back to a mock analysis service if Gemini is unavailable
Mock Analysis Service
Overview
The mock analysis service (mock_analysis_service.py) provides fallback functionality when the Gemini API is unavailable. It uses predefined templates to generate recommendations based on the prediction level.
Implementation
def analyze_prediction(self, user_data, prediction):
"""
Provides a mock analysis when Gemini API is unavailable
Args:
user_data (dict): User input data
prediction: Result from the prediction model
Returns:
str: HTML-formatted analysis
"""
# Extract the score from the prediction
score = self._extract_score(prediction)
# Generate appropriate analysis based on score
if score > 8:
return self._high_risk_template(user_data)
elif score > 5:
return self._moderate_risk_template(user_data)
else:
return self._low_risk_template(user_data)
Data Storage API
Overview
The application stores prediction data in a CSV file for future analysis and model improvement. This functionality is implemented in the prediction_model.py file.
Implementation
def _save_prediction(self, data, prediction):
"""
Saves the prediction to the CSV file
Args:
data (dict): User input data
prediction (str): Prediction result
Returns:
bool: Success status
"""
try:
# Add prediction and timestamp
data['prediction'] = prediction
data['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Load existing CSV and add new row
df = pd.read_csv(self.database_path)
df = pd.concat([df, pd.DataFrame([data])], ignore_index=True)
# Save updated DataFrame
df.to_csv(self.database_path, index=False)
return True
except Exception as e:
print(f"Error saving prediction: {e}")
return False
Future API Enhancements
Potential future API integrations include:
- User Authentication API: Implement user accounts and authentication
- Data Visualization API: Integrate with charting libraries for better data visualization
- Notification API: Send alerts and reminders to users
- Export API: Allow users to export their data and recommendations