Coverage for mindsdb / integrations / handlers / tripadvisor_handler / tripadvisor_handler.py: 0%
107 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-21 00:36 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-21 00:36 +0000
1import os
3import pandas as pd
5from mindsdb.utilities import log
6from mindsdb.utilities.config import Config
8from mindsdb.integrations.libs.api_handler import APIHandler
10from mindsdb.integrations.libs.response import (
11 HandlerStatusResponse as StatusResponse,
12)
14from .tripadvisor_table import SearchLocationTable
15from .tripadvisor_table import LocationDetailsTable
16from .tripadvisor_table import ReviewsTable
17from .tripadvisor_table import PhotosTable
18from .tripadvisor_table import NearbyLocationTable
19from .tripadvisor_api import TripAdvisorAPI
20from .tripadvisor_api import TripAdvisorAPICall
22logger = log.getLogger(__name__)
25class TripAdvisorHandler(APIHandler):
26 """A class for handling connections and interactions with the TripAdvisor Content API.
28 Attributes:
29 api_key (str): The unique API key to access Tripadvisor content.
30 api (TripAdvisorAPI): The `TripAdvisorAPI` object for checking the connection to the TripAdvisor API.
31 """
33 def __init__(self, name=None, **kwargs):
34 super().__init__(name)
36 args = kwargs.get("connection_data", {})
37 self._tables = {}
39 self.connection_args = {}
40 handler_config = Config().get("tripadvisor_handler", {})
41 for k in ["api_key"]:
42 if k in args:
43 self.connection_args[k] = args[k]
44 elif f"TRIPADVISOR_{k.upper()}" in os.environ:
45 self.connection_args[k] = os.environ[f"TRIPADVISOR_{k.upper()}"]
46 elif k in handler_config:
47 self.connection_args[k] = handler_config[k]
49 self.api = None
50 self.is_connected = False
52 tripAdvisor = SearchLocationTable(self)
53 self._register_table("searchLocationTable", tripAdvisor)
55 tripAdvisorLocationDetails = LocationDetailsTable(self)
56 self._register_table("locationDetailsTable", tripAdvisorLocationDetails)
58 tripAdvisorReviews = ReviewsTable(self)
59 self._register_table("reviewsTable", tripAdvisorReviews)
61 tripAdvisorPhotos = PhotosTable(self)
62 self._register_table("photosTable", tripAdvisorPhotos)
64 tripAdvisorNearbyLocation = NearbyLocationTable(self)
65 self._register_table("nearbyLocationTable", tripAdvisorNearbyLocation)
67 def connect(self, api_version=2):
68 """Check the connection with TripAdvisor API"""
70 if self.is_connected is True:
71 return self.api
73 self.api = TripAdvisorAPI(api_key=self.connection_args["api_key"])
75 self.is_connected = True
76 return self.api
78 def check_connection(self) -> StatusResponse:
79 """This function evaluates if the connection is alive and healthy"""
80 response = StatusResponse(False)
82 try:
83 api = self.connect()
85 # make a random http call with searching a location.
86 # it raises an error in case if auth is not success and returns not-found otherwise
87 api.connectTripAdvisor()
88 response.success = True
90 except Exception as e:
91 response.error_message = f"Error connecting to TripAdvisor api: {e}"
92 logger.error(response.error_message)
94 if response.success is False and self.is_connected is True:
95 self.is_connected = False
97 return response
99 def call_tripadvisor_searchlocation_api(
100 self, method_name: str = None, params: dict = None
101 ) -> pd.DataFrame:
102 """It processes the JSON data from the call and transforms it into pandas.Dataframe"""
103 if self.is_connected is False:
104 self.connect()
106 locations = self.api.getTripAdvisorData(
107 TripAdvisorAPICall.SEARCH_LOCATION, **params
108 )
109 result = []
111 for loc in locations:
112 data = {
113 "location_id": loc.get("location_id"),
114 "name": loc.get("name"),
115 "distance": loc.get("distance"),
116 "rating": loc.get("rating"),
117 "bearing": loc.get("bearing"),
118 "street1": loc.get("address_obj").get("street1"),
119 "street2": loc.get("address_obj").get("street2"),
120 "city": loc.get("address_obj").get("city"),
121 "state": loc.get("address_obj").get("state"),
122 "country": loc.get("address_obj").get("country"),
123 "postalcode": loc.get("address_obj").get("postalcode"),
124 "address_string": loc.get("address_obj").get("address_string"),
125 "phone": loc.get("address_obj").get("phone"),
126 "latitude": loc.get("address_obj").get("latitude"),
127 "longitude": loc.get("address_obj").get("longitude"),
128 }
129 result.append(data)
130 result = pd.DataFrame(result)
131 return result
133 def call_tripadvisor_location_details_api(
134 self, method_name: str = None, params: dict = None
135 ) -> pd.DataFrame:
136 """It processes the JSON data from the call and transforms it into pandas.Dataframe"""
137 if self.is_connected is False:
138 self.connect()
140 loc = self.api.getTripAdvisorData(TripAdvisorAPICall.LOCATION_DETAILS, **params)
141 result = []
143 data = {
144 "location_id": loc.get("location_id"),
145 "name": loc.get("name"),
146 "distance": loc.get("distance"),
147 "rating": loc.get("rating"),
148 "bearing": loc.get("bearing"),
149 "street1": loc.get("address_obj").get("street1"),
150 "street2": loc.get("address_obj").get("street2"),
151 "city": loc.get("address_obj").get("city"),
152 "state": loc.get("address_obj").get("state"),
153 "country": loc.get("address_obj").get("country"),
154 "postalcode": loc.get("address_obj").get("postalcode"),
155 "address_string": loc.get("address_obj").get("address_string"),
156 "phone": loc.get("address_obj").get("phone"),
157 "latitude": loc.get("address_obj").get("latitude"),
158 "longitude": loc.get("address_obj").get("longitude"),
159 "web_url": loc.get("web_url"),
160 "timezone": loc.get("timezone"),
161 "email": loc.get("email"),
162 "website": loc.get("website"),
163 "write_review": loc.get("write_review"),
164 "ranking_data": str(loc.get("ranking_data")),
165 "rating_image_url": loc.get("rating_image_url"),
166 "num_reviews": loc.get("num_reviews"),
167 "review_rating_count": loc.get("review_rating_count"),
168 "subratings": loc.get("subratings"),
169 "photo_count": loc.get("photo_count"),
170 "see_all_photos": loc.get("see_all_photos"),
171 "price_level": loc.get("price_level"),
172 "parent_brand": loc.get("parent_brand"),
173 "brand": loc.get("brand"),
174 "ancestors": str(loc.get("ancestors")),
175 "periods": str(loc.get("hours").get("periods"))
176 if loc.get("hours") is not None
177 else None,
178 "weekday": str(loc.get("hours").get("weekday_text"))
179 if loc.get("weekday") is not None
180 else None,
181 "amenities": str(loc.get("amenities")),
182 "features": str(loc.get("features")),
183 "cuisines": str(loc.get("cuisine")),
184 "styles": str(loc.get("styles")),
185 "neighborhood_info": str(loc.get("neighborhood_info")),
186 "awards": str(loc.get("awards")),
187 "trip_types": str(loc.get("trip_types")),
188 "groups": str(loc.get("groups")),
189 }
191 result.append(data)
193 result = pd.DataFrame(result)
194 return result
196 def call_tripadvisor_reviews_api(
197 self, method_name: str = None, params: dict = None
198 ) -> pd.DataFrame:
199 """It processes the JSON data from the call and transforms it into pandas.Dataframe"""
200 if self.is_connected is False:
201 self.connect()
203 locations = self.api.getTripAdvisorData(TripAdvisorAPICall.REVIEWS, **params)
204 result = []
206 for loc in locations:
207 data = {
208 "id": loc.get("id"),
209 "lang": loc.get("lang"),
210 "location_id": loc.get("location_id"),
211 "published_date": loc.get("published_date"),
212 "rating": loc.get("rating"),
213 "helpful_votes": loc.get("helpful_votes"),
214 "rating_image_url": loc.get("rating_image_url"),
215 "url": loc.get("url"),
216 "trip_type": loc.get("trip_type"),
217 "travel_date": loc.get("travel_date"),
218 "text_review": loc.get("text"),
219 "title": loc.get("title"),
220 "owner_response": loc.get("owner_response"),
221 "is_machine_translated": loc.get("is_machine_translated"),
222 "user": str(loc.get("user")),
223 "subratings": str(loc.get("subratings")),
224 }
225 result.append(data)
226 result = pd.DataFrame(result)
227 return result
229 def call_tripadvisor_photos_api(
230 self, method_name: str = None, params: dict = None
231 ) -> pd.DataFrame:
232 """It processes the JSON data from the call and transforms it into pandas.Dataframe"""
233 if self.is_connected is False:
234 self.connect()
236 locations = self.api.getTripAdvisorData(TripAdvisorAPICall.PHOTOS, **params)
237 result = []
239 for loc in locations:
240 data = {
241 "id": loc.get("id"),
242 "is_blessed": loc.get("is_blessed"),
243 "album": loc.get("album"),
244 "caption": loc.get("caption"),
245 "published_date": loc.get("published_date"),
246 "images": str(loc.get("images")),
247 "source": str(loc.get("source")),
248 "user": str(loc.get("user")),
249 }
250 result.append(data)
251 result = pd.DataFrame(result)
252 return result
254 def call_tripadvisor_nearby_location_api(
255 self, method_name: str = None, params: dict = None
256 ) -> pd.DataFrame:
257 """It processes the JSON data from the call and transforms it into pandas.Dataframe"""
258 if self.is_connected is False:
259 self.connect()
261 locations = self.api.getTripAdvisorData(TripAdvisorAPICall.NEARBY_SEARCH, **params)
262 result = []
264 for loc in locations:
265 data = {
266 "location_id": loc.get("location_id"),
267 "name": loc.get("name"),
268 "distance": loc.get("distance"),
269 "rating": loc.get("rating"),
270 "bearing": loc.get("bearing"),
271 "address_obj": str(loc.get("address_obj")),
272 }
273 result.append(data)
274 result = pd.DataFrame(result)
275 return result