help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
real-estate-bot
/
src
RSK World
real-estate-bot
Real Estate Bot - Python + Flask + OpenAI + SQLite + Property Search + AI Chatbot + Viewing Scheduler
src
  • __pycache__
  • __init__.py476 B
  • ai_recommendation_engine.py20.6 KB
  • app.py7.8 KB
  • blockchain_integration.py1.5 KB
  • chatbot.py15.5 KB
  • database.py18.4 KB
  • image_enhancer.py7.9 KB
  • multilang_support.py8.8 KB
  • neighborhood_analyzer.py6.1 KB
  • price_prediction_engine.py25.1 KB
  • property_search.py15.6 KB
  • virtual_tour_manager.py21.8 KB
  • voice_assistant.py27.6 KB
neighborhood_analyzer.pyproperty_search.py
src/neighborhood_analyzer.py
Raw Download
Find: Go to:
"""
Neighborhood Insights and Crime Rate Analysis
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: info@rskworld.com, +91 93305 39277
Year: 2026
"""

import os
import requests
import json
from typing import Dict, Any, List
from datetime import datetime
import numpy as np

class NeighborhoodAnalyzer:
    def __init__(self):
        self.api_keys = {
            'google_places': os.getenv('GOOGLE_PLACES_API_KEY'),
            'crime_api': os.getenv('CRIME_API_KEY')
        }
    
    def analyze_neighborhood(self, location: str) -> Dict[str, Any]:
        """Comprehensive neighborhood analysis"""
        return {
            'safety_score': self._get_safety_score(location),
            'amenities': self._get_nearby_amenities(location),
            'schools': self._get_school_ratings(location),
            'transport': self._get_transport_info(location),
            'demographics': self._get_demographics(location)
        }
    
    def _get_safety_score(self, location: str) -> float:
        """Get safety score for location (0-10 scale)"""
        # This would typically use crime data APIs
        # For now, return a mock score based on location
        location_lower = location.lower()
        
        # Higher safety scores for major metropolitan areas
        if any(city in location_lower for city in ['mumbai', 'bangalore', 'pune', 'hyderabad']):
            return 7.5
        elif any(city in location_lower for city in ['delhi', 'chennai', 'kolkata']):
            return 7.0
        else:
            return 6.5  # Default score
    
    def _get_nearby_amenities(self, location: str) -> List[Dict[str, Any]]:
        """Get nearby amenities for location"""
        # This would typically use Google Places API
        # For now, return mock data
        amenities = [
            {'type': 'hospital', 'name': 'Nearby Hospital', 'distance': '2 km', 'rating': 4.5},
            {'type': 'school', 'name': 'Local School', 'distance': '1 km', 'rating': 4.2},
            {'type': 'shopping', 'name': 'Shopping Mall', 'distance': '3 km', 'rating': 4.3},
            {'type': 'restaurant', 'name': 'Restaurant Hub', 'distance': '1.5 km', 'rating': 4.4},
            {'type': 'park', 'name': 'Community Park', 'distance': '0.5 km', 'rating': 4.6}
        ]
        return amenities
    
    def _get_school_ratings(self, location: str) -> Dict[str, Any]:
        """Get school ratings for location"""
        # Mock data - would use education APIs in production
        return {
            'primary_schools': [
                {'name': 'Local Primary School', 'rating': 4.3, 'distance': '1 km'},
                {'name': 'Community Primary', 'rating': 4.1, 'distance': '1.5 km'}
            ],
            'secondary_schools': [
                {'name': 'Local Secondary School', 'rating': 4.5, 'distance': '2 km'},
                {'name': 'High School', 'rating': 4.4, 'distance': '2.5 km'}
            ],
            'colleges': [
                {'name': 'Nearby College', 'rating': 4.2, 'distance': '5 km'}
            ],
            'average_rating': 4.3
        }
    
    def _get_transport_info(self, location: str) -> Dict[str, Any]:
        """Get transportation information for location"""
        # Mock data - would use transit APIs in production
        location_lower = location.lower()
        
        has_metro = any(city in location_lower for city in ['delhi', 'bangalore', 'mumbai', 'chennai', 'kolkata', 'hyderabad'])
        
        return {
            'metro_available': has_metro,
            'metro_stations': [
                {'name': 'Nearest Metro Station', 'distance': '2 km', 'line': 'Blue Line'}
            ] if has_metro else [],
            'bus_stops': [
                {'name': 'Bus Stop 1', 'distance': '0.3 km'},
                {'name': 'Bus Stop 2', 'distance': '0.5 km'}
            ],
            'railway_station': {
                'name': 'Nearest Railway Station',
                'distance': '5 km',
                'available': True
            },
            'airport_distance': '25 km',
            'connectivity_score': 8.5 if has_metro else 7.0
        }
    
    def _get_demographics(self, location: str) -> Dict[str, Any]:
        """Get demographic information for location"""
        # Mock demographic data - would use census/statistics APIs in production
        return {
            'population_density': 'Medium',
            'average_age': 32,
            'family_composition': {
                'families_with_children': 65,
                'young_professionals': 25,
                'senior_citizens': 10
            },
            'income_level': 'Upper Middle Class',
            'languages_spoken': ['Hindi', 'English', 'Local Language'],
            'religious_diversity': 'High',
            'education_level': 'Above Average'
        }
    
    def get_location_rating(self, location: str) -> Dict[str, Any]:
        """Get overall location rating with factors"""
        analysis = self.analyze_neighborhood(location)
        
        # Calculate overall rating
        safety_score = analysis['safety_score']
        connectivity_score = analysis['transport'].get('connectivity_score', 7.0)
        amenities_count = len(analysis['amenities'])
        schools_rating = analysis['schools'].get('average_rating', 4.0)
        
        overall_rating = (
            (safety_score / 10) * 0.3 +
            (connectivity_score / 10) * 0.25 +
            (min(amenities_count, 10) / 10) * 0.25 +
            (schools_rating / 5) * 0.2
        ) * 10
        
        return {
            'location': location,
            'overall_rating': round(overall_rating, 2),
            'safety_rating': round(safety_score, 2),
            'connectivity_rating': round(connectivity_score, 1),
            'amenities_rating': round((amenities_count / 10) * 10, 1),
            'schools_rating': round((schools_rating / 5) * 10, 1),
            'factors': analysis,
            'recommendation': 'Excellent' if overall_rating >= 8 else 'Good' if overall_rating >= 7 else 'Average'
        }
147 lines•6.1 KB
python
src/property_search.py
Raw Download
Find: Go to:
"""
Property Search Engine for Real Estate Bot
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: info@rskworld.com, +91 93305 39277
Year: 2026
"""

import requests
import json
from typing import List, Dict, Any, Optional
try:
    from .database import DatabaseManager
except ImportError:
    # Fallback for direct import
    from database import DatabaseManager

class PropertySearchEngine:
    def __init__(self, api_key: str = None, api_url: str = None):
        """
        Initialize Property Search Engine
        
        Args:
            api_key: External API key (optional)
            api_url: External API URL (optional)
        """
        self.api_key = api_key
        self.api_url = api_url
        self.db_manager = DatabaseManager()
        
    def search(self, criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        Search properties based on criteria
        
        Args:
            criteria: Search criteria dictionary containing:
                     - location: string
                     - property_type: string
                     - price_min: float
                     - price_max: float
                     - bedrooms: int
                     - bathrooms: int
                     - area_min: float
                     - area_max: float
                     - amenities: list
                     - limit: int (default 10)
        
        Returns:
            List of matching properties
        """
        try:
            # First try local database search
            local_results = self.db_manager.search_properties(criteria)
            
            # If external API is configured, fetch additional results
            if self.api_key and self.api_url:
                external_results = self._search_external_api(criteria)
                # Merge and deduplicate results
                all_results = self._merge_results(local_results, external_results)
            else:
                all_results = local_results
            
            # Apply additional filtering and ranking
            filtered_results = self._apply_advanced_filters(all_results, criteria)
            ranked_results = self._rank_properties(filtered_results, criteria)
            
            # Limit results
            limit = criteria.get('limit', 10)
            return ranked_results[:limit]
            
        except Exception as e:
            print(f"Error in property search: {e}")
            return []
    
    def get_property_by_id(self, property_id: int) -> Optional[Dict[str, Any]]:
        """
        Get detailed property information by ID
        
        Args:
            property_id: Property ID
            
        Returns:
            Property details or None if not found
        """
        try:
            # First check local database
            property_info = self.db_manager.get_property_by_id(property_id)
            
            if property_info:
                return property_info
            
            # If not found locally and external API is available, try external search
            if self.api_key and self.api_url:
                return self._get_external_property(property_id)
            
            return None
            
        except Exception as e:
            print(f"Error getting property by ID: {e}")
            return None
    
    def get_similar_properties(self, property_id: int, limit: int = 5) -> List[Dict[str, Any]]:
        """
        Get similar properties based on property characteristics
        
        Args:
            property_id: Reference property ID
            limit: Maximum number of similar properties
            
        Returns:
            List of similar properties
        """
        try:
            # Get reference property
            ref_property = self.get_property_by_id(property_id)
            if not ref_property:
                return []
            
            # Create similarity criteria
            criteria = {
                'property_type': ref_property.get('property_type'),
                'price_min': ref_property.get('price', 0) * 0.8,
                'price_max': ref_property.get('price', 0) * 1.2,
                'bedrooms': ref_property.get('bedrooms'),
                'location': ref_property.get('location'),
                'limit': limit + 1  # Get one extra to exclude the reference property
            }
            
            # Search for similar properties
            similar_properties = self.search(criteria)
            
            # Remove the reference property from results
            similar_properties = [p for p in similar_properties if p['id'] != property_id]
            
            return similar_properties[:limit]
            
        except Exception as e:
            print(f"Error getting similar properties: {e}")
            return []
    
    def get_property_recommendations(self, user_preferences: Dict[str, Any], limit: int = 10) -> List[Dict[str, Any]]:
        """
        Get property recommendations based on user preferences
        
        Args:
            user_preferences: User preference dictionary
            limit: Maximum number of recommendations
            
        Returns:
            List of recommended properties
        """
        try:
            # Convert user preferences to search criteria
            criteria = {
                'location': user_preferences.get('preferred_locations'),
                'property_type': user_preferences.get('preferred_types'),
                'price_max': user_preferences.get('max_budget'),
                'bedrooms': user_preferences.get('preferred_bedrooms'),
                'limit': limit
            }
            
            # Search for matching properties
            recommendations = self.search(criteria)
            
            # Apply preference-based ranking
            ranked_recommendations = self._rank_by_preferences(recommendations, user_preferences)
            
            return ranked_recommendations
            
        except Exception as e:
            print(f"Error getting property recommendations: {e}")
            return []
    
    def _search_external_api(self, criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        Search properties using external API
        
        Args:
            criteria: Search criteria
            
        Returns:
            List of properties from external API
        """
        try:
            headers = {
                'Authorization': f'Bearer {self.api_key}',
                'Content-Type': 'application/json'
            }
            
            # Convert criteria to API format
            api_params = self._convert_criteria_to_api_format(criteria)
            
            response = requests.get(
                f"{self.api_url}/properties/search",
                headers=headers,
                params=api_params,
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                return self._convert_api_response_to_properties(data)
            else:
                print(f"External API error: {response.status_code}")
                return []
                
        except Exception as e:
            print(f"Error searching external API: {e}")
            return []
    
    def _get_external_property(self, property_id: int) -> Optional[Dict[str, Any]]:
        """
        Get property from external API
        
        Args:
            property_id: Property ID
            
        Returns:
            Property details or None
        """
        try:
            headers = {
                'Authorization': f'Bearer {self.api_key}',
                'Content-Type': 'application/json'
            }
            
            response = requests.get(
                f"{self.api_url}/properties/{property_id}",
                headers=headers,
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                return self._convert_api_property_to_property(data)
            else:
                return None
                
        except Exception as e:
            print(f"Error getting external property: {e}")
            return None
    
    def _convert_criteria_to_api_format(self, criteria: Dict[str, Any]) -> Dict[str, Any]:
        """Convert internal criteria to external API format"""
        api_params = {}
        
        if criteria.get('location'):
            api_params['location'] = criteria['location']
        
        if criteria.get('property_type'):
            api_params['type'] = criteria['property_type']
        
        if criteria.get('price_min'):
            api_params['minPrice'] = criteria['price_min']
        
        if criteria.get('price_max'):
            api_params['maxPrice'] = criteria['price_max']
        
        if criteria.get('bedrooms'):
            api_params['bedrooms'] = criteria['bedrooms']
        
        if criteria.get('bathrooms'):
            api_params['bathrooms'] = criteria['bathrooms']
        
        return api_params
    
    def _convert_api_response_to_properties(self, api_data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Convert external API response to internal property format"""
        properties = []
        
        for item in api_data.get('properties', []):
            property_data = self._convert_api_property_to_property(item)
            if property_data:
                properties.append(property_data)
        
        return properties
    
    def _convert_api_property_to_property(self, api_property: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """Convert single API property to internal format"""
        try:
            return {
                'id': api_property.get('id'),
                'title': api_property.get('title', 'Property'),
                'description': api_property.get('description', ''),
                'price': api_property.get('price', 0),
                'location': api_property.get('location', ''),
                'property_type': api_property.get('type', 'unknown'),
                'bedrooms': api_property.get('bedrooms', 0),
                'bathrooms': api_property.get('bathrooms', 0),
                'area_sqft': api_property.get('area', 0),
                'year_built': api_property.get('yearBuilt', 0),
                'amenities': api_property.get('amenities', []),
                'images': api_property.get('images', []),
                'created_at': api_property.get('createdAt', '')
            }
        except Exception as e:
            print(f"Error converting API property: {e}")
            return None
    
    def _merge_results(self, local_results: List[Dict[str, Any]], external_results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """Merge local and external results, removing duplicates"""
        all_results = local_results.copy()
        
        # Track property IDs to avoid duplicates
        existing_ids = {prop['id'] for prop in local_results}
        
        # Add external results that aren't duplicates
        for prop in external_results:
            if prop['id'] not in existing_ids:
                all_results.append(prop)
                existing_ids.add(prop['id'])
        
        return all_results
    
    def _apply_advanced_filters(self, properties: List[Dict[str, Any]], criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Apply advanced filtering to property results"""
        filtered_properties = []
        
        for prop in properties:
            # Filter by area
            if criteria.get('area_min') and prop.get('area_sqft', 0) < criteria['area_min']:
                continue
            
            if criteria.get('area_max') and prop.get('area_sqft', 0) > criteria['area_max']:
                continue
            
            # Filter by amenities
            if criteria.get('amenities'):
                prop_amenities = set(prop.get('amenities', []))
                required_amenities = set(criteria['amenities'])
                
                if not required_amenities.issubset(prop_amenities):
                    continue
            
            # Filter by year built
            if criteria.get('year_built_min') and prop.get('year_built', 0) < criteria['year_built_min']:
                continue
            
            filtered_properties.append(prop)
        
        return filtered_properties
    
    def _rank_properties(self, properties: List[Dict[str, Any]], criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Rank properties based on relevance to criteria"""
        def calculate_score(property_data):
            score = 0
            
            # Location match (highest weight)
            if criteria.get('location') and criteria['location'].lower() in property_data.get('location', '').lower():
                score += 30
            
            # Property type match
            if criteria.get('property_type') and criteria['property_type'] == property_data.get('property_type'):
                score += 20
            
            # Bedroom match
            if criteria.get('bedrooms') and criteria['bedrooms'] == property_data.get('bedrooms'):
                score += 15
            
            # Price range match
            price = property_data.get('price', 0)
            if criteria.get('price_min') and price >= criteria['price_min']:
                score += 10
            if criteria.get('price_max') and price <= criteria['price_max']:
                score += 10
            
            # Recency (newer properties get higher score)
            score += 5
            
            return score
        
        # Sort by score (descending)
        ranked_properties = sorted(properties, key=calculate_score, reverse=True)
        return ranked_properties
    
    def _rank_by_preferences(self, properties: List[Dict[str, Any]], preferences: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Rank properties based on user preferences"""
        def calculate_preference_score(property_data):
            score = 0
            
            # Preferred locations
            preferred_locations = preferences.get('preferred_locations', [])
            if preferred_locations:
                for location in preferred_locations:
                    if location.lower() in property_data.get('location', '').lower():
                        score += 25
                        break
            
            # Preferred property types
            preferred_types = preferences.get('preferred_types', [])
            if property_data.get('property_type') in preferred_types:
                score += 20
            
            # Budget preference
            max_budget = preferences.get('max_budget', 0)
            if max_budget and property_data.get('price', 0) <= max_budget:
                score += 15
            
            # Amenity preferences
            preferred_amenities = preferences.get('preferred_amenities', [])
            if preferred_amenities:
                prop_amenities = set(property_data.get('amenities', []))
                matching_amenities = len(set(preferred_amenities) & prop_amenities)
                score += matching_amenities * 5
            
            return score
        
        return sorted(properties, key=calculate_preference_score, reverse=True)
410 lines•15.6 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer