forked from mordax7/flathunter
-
Notifications
You must be signed in to change notification settings - Fork 183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Google Maps filter #473
Open
colinemonds
wants to merge
4
commits into
flathunters:main
Choose a base branch
from
colinemonds:google-maps-filter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Google Maps filter #473
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
1dad3d4
refactor: separate GMaps process from format
colinemondswieprecht 1c5f36b
fix unit test on Windows
colinemondswieprecht 8a85d82
feature #472: filter based on GMaps distance
colinemondswieprecht 74d41fc
Merge remote-tracking branch 'origin/main' into google-maps-filter
colinemondswieprecht File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
from dataclasses import dataclass | ||
from enum import Enum | ||
from typing import Optional | ||
|
||
|
||
class TransportationModes(Enum): | ||
"""The transportation mode for Google Maps distance calculation.""" | ||
TRANSIT = 'transit' | ||
BICYCLING = 'bicycling' | ||
DRIVING = 'driving' | ||
WALKING = 'walking' | ||
|
||
|
||
@dataclass | ||
class DistanceValueTuple: | ||
"""We want to keep both the numeric value of a distance, and its string representation.""" | ||
meters: float | ||
text: str | ||
|
||
|
||
@dataclass | ||
class DurationValueTuple: | ||
"""We want to keep both the numeric value of a duration, and its string representation.""" | ||
seconds: float | ||
text: str | ||
|
||
|
||
@dataclass | ||
class DistanceElement: | ||
"""Represents the distance from a property to some location.""" | ||
duration: DurationValueTuple | ||
distance: DistanceValueTuple | ||
mode: TransportationModes | ||
|
||
|
||
@dataclass | ||
class DistanceConfig: | ||
"""Represents distance filter information in the configuration file. | ||
|
||
location_name must refer to the location name used to identify the location | ||
in the durations section of the config file, and the transport_mode must be | ||
configured in the durations section for that location name, lest no information | ||
is available to actually filter on.""" | ||
location_name: str | ||
transport_mode: TransportationModes | ||
max_distance_meters: Optional[float] | ||
max_duration_seconds: Optional[float] | ||
|
||
|
||
class FilterChainName(Enum): | ||
"""Identifies the filter chain that a filter acts on | ||
|
||
Preprocess filters will be run before the expose is processed by any further actions. | ||
Use this chain to filter exposes that can be excluded based on information scraped | ||
from the expose website alone (such as based on price or size). | ||
Postprocess filters will be run after other actions have completed. Use this if you | ||
require additional information from other steps, such as information from the Google | ||
Maps API, to make a decision on this expose. | ||
|
||
We separate the filter chains to avoid making expensive (literally!) calls to the | ||
Google Maps API for exposes that we already know we aren't interested in anyway.""" | ||
preprocess = 'PREPROCESS' | ||
postprocess = 'POSTPROCESS' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,12 @@ | ||
"""Module with implementations of standard expose filters""" | ||
from functools import reduce | ||
import re | ||
from abc import ABC, ABCMeta | ||
from typing import List, Any | ||
from typing import List, Any, Dict | ||
|
||
from flathunter.config import DistanceConfig | ||
from flathunter.dataclasses import FilterChainName | ||
from flathunter.gmaps_duration_processor import DistanceElement | ||
from flathunter.logging import logger | ||
|
||
|
||
class AbstractFilter(ABC): | ||
|
@@ -172,30 +176,65 @@ def is_interesting(self, expose): | |
return pps <= self.max_pps | ||
|
||
|
||
class FilterBuilder: | ||
class DistanceFilter(AbstractFilter): | ||
"""Exclude properties based on distance or duration to a location | ||
|
||
This must be in the post-processing filter chain, as it requires data | ||
from the Google Maps API, which is not available right after scraping.""" | ||
|
||
distance_config: DistanceConfig | ||
|
||
def __init__(self, distance_config: DistanceConfig): | ||
self.distance_config = distance_config | ||
|
||
def is_interesting(self, expose): | ||
durations: Dict[str, DistanceElement] = expose.get('durations_unformatted', None) | ||
if durations is None or self.distance_config.location_name not in durations: | ||
logger.info('DurationFilter is enabled, but no GMaps data found. Skipping filter.') | ||
return True | ||
distance = durations[self.distance_config.location_name].distance.meters | ||
duration = durations[self.distance_config.location_name].duration.seconds | ||
out = True | ||
if self.distance_config.max_distance_meters: | ||
out &= distance < self.distance_config.max_distance_meters | ||
if self.distance_config.max_duration_seconds: | ||
out &= duration < self.distance_config.max_duration_seconds | ||
return out | ||
|
||
|
||
class FilterChainBuilder: | ||
"""Construct a filter chain""" | ||
filters: List[AbstractFilter] | ||
|
||
def __init__(self): | ||
self.filters = [] | ||
|
||
def _append_filter_if_not_empty(self, filter_class: ABCMeta, filter_config: Any): | ||
def _append_filter_if_not_empty( | ||
self, | ||
filter_class: ABCMeta, | ||
filter_config: Any): | ||
"""Appends a filter to the list if its configuration is set""" | ||
if not filter_config: | ||
return | ||
self.filters.append(filter_class(filter_config)) | ||
|
||
def read_config(self, config): | ||
def read_config(self, config, filter_chain: FilterChainName): | ||
"""Adds filters from a config dictionary""" | ||
self._append_filter_if_not_empty(TitleFilter, config.excluded_titles()) | ||
self._append_filter_if_not_empty(MinPriceFilter, config.min_price()) | ||
self._append_filter_if_not_empty(MaxPriceFilter, config.max_price()) | ||
self._append_filter_if_not_empty(MinSizeFilter, config.min_size()) | ||
self._append_filter_if_not_empty(MaxSizeFilter, config.max_size()) | ||
self._append_filter_if_not_empty(MinRoomsFilter, config.min_rooms()) | ||
self._append_filter_if_not_empty(MaxRoomsFilter, config.max_rooms()) | ||
self._append_filter_if_not_empty( | ||
PPSFilter, config.max_price_per_square()) | ||
if filter_chain == FilterChainName.preprocess: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm a bit "meh" on if-else chains. Do you think we could do this with Enum and Match? https://realpython.com/python-enum/#using-enumerations-in-if-and-match-statements |
||
self._append_filter_if_not_empty(TitleFilter, config.excluded_titles()) | ||
self._append_filter_if_not_empty(MinPriceFilter, config.min_price()) | ||
self._append_filter_if_not_empty(MaxPriceFilter, config.max_price()) | ||
self._append_filter_if_not_empty(MinSizeFilter, config.min_size()) | ||
self._append_filter_if_not_empty(MaxSizeFilter, config.max_size()) | ||
self._append_filter_if_not_empty(MinRoomsFilter, config.min_rooms()) | ||
self._append_filter_if_not_empty(MaxRoomsFilter, config.max_rooms()) | ||
self._append_filter_if_not_empty( | ||
PPSFilter, config.max_price_per_square()) | ||
elif filter_chain == FilterChainName.postprocess: | ||
for df in config.max_distance(): | ||
self._append_filter_if_not_empty(DistanceFilter, df) | ||
else: | ||
raise NotImplementedError() | ||
return self | ||
|
||
def filter_already_seen(self, id_watch): | ||
|
@@ -204,12 +243,12 @@ def filter_already_seen(self, id_watch): | |
return self | ||
|
||
def build(self): | ||
"""Return the compiled filter""" | ||
return Filter(self.filters) | ||
"""Return the compiled filter chain""" | ||
return FilterChain(self.filters) | ||
|
||
|
||
class Filter: | ||
"""Abstract filter object""" | ||
class FilterChain: | ||
"""Collection of expose filters in use by a hunter instance""" | ||
|
||
filters: List[AbstractFilter] | ||
|
||
|
@@ -218,14 +257,17 @@ def __init__(self, filters: List[AbstractFilter]): | |
|
||
def is_interesting_expose(self, expose): | ||
"""Apply all filters to this expose""" | ||
return reduce((lambda x, y: x and y), | ||
map((lambda x: x.is_interesting(expose)), self.filters), True) | ||
|
||
for filter_ in self.filters: | ||
if not filter_.is_interesting(expose): | ||
return False | ||
return True | ||
|
||
def filter(self, exposes): | ||
"""Apply all filters to every expose in the list""" | ||
return filter(self.is_interesting_expose, exposes) | ||
|
||
@staticmethod | ||
def builder(): | ||
"""Return a new filter builder""" | ||
return FilterBuilder() | ||
"""Return a new filter chain builder""" | ||
return FilterChainBuilder() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if it would be more natural here just to return the empty list of there's nothing configured. Makes the typing judgement simpler.