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
requirements.txtsentiment-analysis-bot.pngproperty_search.py
requirements.txt
Raw Download
Find: Go to:
flask==2.3.3
openai==1.3.5
requests==2.31.0
python-dotenv==1.0.0
flask-cors==4.0.0
jinja2==3.1.2
gunicorn==21.2.0
numpy==1.24.3
pandas==2.0.3
scikit-learn==1.3.0
opencv-python==4.8.1.78
Pillow==10.0.1
speechrecognition==3.10.0
pyttsx3==2.90
joblib==1.3.2
web3==6.11.0
17 lines•284 B
text
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
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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