Anupam251272's picture
Update app.py
0182177 verified
import gradio as gr
from dataclasses import dataclass
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import requests
from astral import LocationInfo
from astral.sun import sun
import os
from enum import Enum
import logging
import re
import random
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class YearlyPrediction:
year: int
theme: str
career: Dict[str, str]
love: Dict[str, str]
health: Dict[str, str]
growth_potential: float
harmony_level: float
vitality_level: float
class PredictionThemes(Enum):
ABUNDANCE = "ABUNDANCE"
TRANSFORMATION = "TRANSFORMATION"
GROWTH = "GROWTH"
MANIFESTATION = "MANIFESTATION"
@dataclass
class LocationDetails:
latitude: float
longitude: float
timezone: str
city: str
country: str
class PredictionDatabase:
"""Enhanced prediction database with more detailed data."""
def __init__(self):
self._initialize_databases()
def _initialize_databases(self):
self.focus_areas = [
"Technology", "Politics", "Sports", "Business", "Education",
"Arts", "Science", "Healthcare", "Finance", "Media"
]
self.opportunities = [
"Lead major initiative", "Career advancement",
"Start new venture", "Launch innovative project"
]
self.love_developments = [
"Meaningful commitment", "Deeper emotional connection",
"Exciting shared adventures", "Strong emotional bonds"
]
self.activities = [
"Creative Projects", "Travel", "Sports",
"Cultural Events", "Social Gatherings"
]
self.health_focuses = [
"Active lifestyle habits", "Regular exercise routine",
"Stress-relief techniques", "Balanced nutrition"
]
self.health_practices = [
"Leadership Roles", "High-Intensity Training",
"Mindfulness Practice", "Team Sports"
]
class PredictionGenerator:
"""Enhanced prediction generator with detailed formatting."""
def __init__(self):
self.db = PredictionDatabase()
def generate_five_year_prediction(self, name: str, start_year: int,
birth_time: str, location: LocationDetails) -> str:
predictions = []
for year in range(start_year, start_year + 5):
predictions.append(self._generate_yearly_prediction(year))
return self._format_comprehensive_prediction(
name, birth_time, location, predictions
)
def _generate_yearly_prediction(self, year: int) -> YearlyPrediction:
"""Generate detailed prediction for a specific year."""
return YearlyPrediction(
year=year,
theme=random.choice(list(PredictionThemes)).value,
career={
"focus_area": random.choice(self.db.focus_areas),
"opportunity": random.choice(self.db.opportunities),
"peak_months": ", ".join(sorted(random.sample([
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
], 3)))
},
love={
"development": random.choice(self.db.love_developments),
"activity": random.choice(self.db.activities),
"peak_months": ", ".join(sorted(random.sample([
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
], 2)))
},
health={
"focus": random.choice(self.db.health_focuses),
"practice": random.choice(self.db.health_practices),
"peak_months": ", ".join(sorted(random.sample([
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
], 3)))
},
growth_potential=random.uniform(80, 98),
harmony_level=random.uniform(80, 99),
vitality_level=random.uniform(85, 97)
)
def _format_comprehensive_prediction(self, name: str, birth_time: str,
location: LocationDetails,
predictions: List[YearlyPrediction]) -> str:
"""Format the comprehensive prediction with all details."""
output = f"""๐ŸŒŸ COMPREHENSIVE LIFE PATH PREDICTION FOR {name.upper()} ๐ŸŒŸ
=========================================================
๐Ÿ“Š CORE NUMEROLOGICAL PROFILE
----------------------------
Birth Time: {birth_time}
Location: {location.city} ({location.country})
๐Ÿ”ฎ 5-YEAR LIFE FORECAST (Year by Year Analysis)
---------------------------------------------
"""
# Add yearly predictions
for pred in predictions:
output += f"""
{pred.year} - YEAR OF {pred.theme}
-------------------------------------------------------------------
๐Ÿ’ผ Career Path:
โ€ข Focus Area: {pred.career['focus_area']}
โ€ข Key Opportunity: {pred.career['opportunity']}
โ€ข Peak Months: {pred.career['peak_months']}
โ€ข Growth Potential: {pred.growth_potential:.1f}%
โค๏ธ Love & Relationships:
โ€ข Key Development: {pred.love['development']}
โ€ข Recommended Activity: {pred.love['activity']}
โ€ข Romantic Peaks: {pred.love['peak_months']}
โ€ข Harmony Level: {pred.harmony_level:.1f}%
๐ŸŒฟ Health & Wellness:
โ€ข Focus Area: {pred.health['focus']}
โ€ข Recommended Practice: {pred.health['practice']}
โ€ข Peak Vitality Months: {pred.health['peak_months']}
โ€ข Vitality Level: {pred.vitality_level:.1f}%
"""
# Add final sections
output += """
๐ŸŒˆ INTEGRATED LIFE HARMONY ANALYSIS
---------------------------------
Your numbers reveal a beautiful synchronicity between career growth,
personal relationships, and health developments. Each aspect supports
and enhances the others, creating a harmonious life trajectory.
Key Integration Points:
โ€ข Career achievements positively impact relationship confidence
โ€ข Relationship growth supports emotional and physical well-being
โ€ข Health improvements boost career performance and relationship energy
๐Ÿ’ซ GUIDANCE FOR OPTIMAL GROWTH
----------------------------
1. Embrace each opportunity for growth across all life areas
2. Maintain balance between professional ambitions and personal life
3. Practice self-care to sustain energy for both career and relationships
4. Trust your intuition in making life decisions
5. Stay open to unexpected opportunities and connections
๐ŸŒŸ FINAL WISDOM
--------------
This five-year period shows exceptional promise for personal growth,
professional achievement, and meaningful relationships. Your unique
numerical vibration suggests a time of positive transformation and
fulfilling experiences across all life areas."""
return output
def create_gradio_interface() -> gr.Interface:
"""Create and configure the Gradio interface."""
def predict(name: str, dob: str, birth_time: str, birth_place: str) -> str:
"""Main prediction function for Gradio interface."""
try:
# Validate inputs
error = validate_inputs(name, dob, birth_time, birth_place)
if error:
return error
# Create location details (simplified for example)
location = LocationDetails(
latitude=27.6094, # Example coordinates for Sikar
longitude=75.1398,
timezone="Asia/Kolkata",
city=birth_place.split(',')[0].strip(),
country="India" if "India" in birth_place else "Unknown"
)
# Generate prediction
generator = PredictionGenerator()
current_year = datetime.now().year
prediction = generator.generate_five_year_prediction(
name, current_year, birth_time, location
)
return prediction
except Exception as e:
logger.error(f"Error in prediction: {e}")
return f"An error occurred: {str(e)}"
return gr.Interface(
fn=predict,
inputs=[
gr.Textbox(label="Full Name", placeholder="Enter your full name"),
gr.Textbox(label="Date of Birth (YYYY-MM-DD)", placeholder="e.g., 1990-05-15"),
gr.Textbox(label="Birth Time (HH:MM)", placeholder="e.g., 14:30"),
gr.Textbox(label="Birth Place", placeholder="e.g., Sikar, Rajasthan, India")
],
outputs=gr.Textbox(label="Your Comprehensive Life Path Prediction"),
title="๐ŸŒŸ Quantum Life Path Prediction System",
description="Discover your quantum numerological blueprint!"
)
def validate_inputs(name: str, dob: str, birth_time: str, birth_place: str) -> Optional[str]:
"""Validate all input parameters."""
if not all([name, dob, birth_time, birth_place]):
return "All fields are required."
if not name.strip():
return "Name cannot be empty."
if not re.match(r"^\d{2}:\d{2}$", birth_time):
return "Invalid time format. Use HH:MM."
try:
datetime.strptime(dob, "%Y-%m-%d")
except ValueError:
return "Invalid date format. Use YYYY-MM-DD."
return None
if __name__ == "__main__":
interface = create_gradio_interface()
interface.launch(debug=True)