-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.py
More file actions
197 lines (155 loc) · 5.4 KB
/
Copy pathsearch.py
File metadata and controls
197 lines (155 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""
MobileAPI Interactive Search Demo
A command-line tool demonstrating MobileAPI's fuzzy search and autocomplete
capabilities. Type a query to see matching devices with confidence scores.
Usage:
export MOBILEAPI_KEY="your_api_key_here"
python search.py
# Or run a single search:
python search.py "iPhone 16"
Get your free API key: https://mobileapi.dev/signup/
API docs: https://mobileapi.dev/docs/
"""
import os
import sys
# Add parent directory to path so we can import the SDK
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "sdk"))
from mobileapi import MobileAPI, MobileAPIError, RateLimitError
def print_header():
"""Print the welcome header."""
print()
print("=" * 60)
print(" MobileAPI Search Demo")
print(" Search 27,000+ devices with fuzzy matching")
print("=" * 60)
print()
def print_search_results(data: dict) -> None:
"""Format and print search results with match confidence."""
results = data.get("results", [])
total = data.get("total", 0)
page = data.get("page", 1)
total_pages = data.get("total_pages", 1)
if not results:
print(" No devices found. Try a different search term.")
print()
return
print(f" Found {total} device(s) (page {page}/{total_pages})")
print("-" * 60)
print()
for i, device in enumerate(results, 1):
name = device.get("name", "Unknown")
certainty = device.get("match_certainty", "N/A")
match_type = device.get("match_type", "")
device_id = device.get("id", "?")
# Certainty color indicator
if isinstance(certainty, (int, float)):
if certainty == 100:
indicator = "[EXACT]"
elif certainty >= 85:
indicator = "[HIGH] "
elif certainty >= 70:
indicator = "[FAIR] "
else:
indicator = "[LOW] "
certainty_str = f"{certainty}%"
else:
indicator = " "
certainty_str = str(certainty)
print(f" {i:2d}. {name}")
print(f" ID: {device_id} | Match: {certainty_str} {indicator}", end="")
if match_type:
print(f" | Type: {match_type}", end="")
print()
print()
print("-" * 60)
def print_autocomplete_results(data: dict) -> None:
"""Format and print autocomplete suggestions."""
results = data.get("results", [])
if not results:
print(" No suggestions found.")
print()
return
print(f" {len(results)} suggestion(s):")
print()
for i, device in enumerate(results, 1):
name = device.get("name", "Unknown")
device_id = device.get("id", "?")
print(f" {i:2d}. {name} (ID: {device_id})")
print()
def interactive_mode(api: MobileAPI) -> None:
"""Run the interactive search loop."""
print("Commands:")
print(" Type a device name to search (e.g., 'Samsung Galaxy S25')")
print(" Prefix with 'a:' for autocomplete (e.g., 'a:sam gal')")
print(" Type 'quit' or 'q' to exit")
print()
while True:
try:
query = input("search> ").strip()
except (EOFError, KeyboardInterrupt):
print("\nGoodbye!")
break
if not query:
continue
if query.lower() in ("quit", "q", "exit"):
print("Goodbye!")
break
try:
if query.startswith("a:"):
# Autocomplete mode
term = query[2:].strip()
if not term:
print(" Usage: a:<search term> (e.g., a:iphone)")
print()
continue
print(f"\n Autocomplete for: \"{term}\"")
data = api.autocomplete(name=term, limit=10)
print_autocomplete_results(data)
else:
# Full search mode
print(f"\n Searching for: \"{query}\"")
print()
data = api.search_devices(name=query, limit=10)
print_search_results(data)
except RateLimitError as exc:
print(f"\n Rate limit reached. Please wait and try again.")
if exc.retry_after:
print(f" Retry after: {exc.retry_after} seconds")
print()
except MobileAPIError as exc:
print(f"\n API error: {exc}")
print()
def single_search(api: MobileAPI, query: str) -> None:
"""Run a single search and print results."""
print(f" Searching for: \"{query}\"")
print()
try:
data = api.search_devices(name=query, limit=10)
print_search_results(data)
except MobileAPIError as exc:
print(f" Error: {exc}")
sys.exit(1)
def main():
"""Entry point."""
print_header()
# Initialize API client
try:
api = MobileAPI()
except Exception as exc:
print(f" Error: {exc}")
print()
print(" Set your API key:")
print(" export MOBILEAPI_KEY='your_api_key_here'")
print()
print(" Get a free key at: https://mobileapi.dev/signup/")
sys.exit(1)
print(f" API key loaded. Ready to search!")
print()
# Check if a query was passed as a command-line argument
if len(sys.argv) > 1:
query = " ".join(sys.argv[1:])
single_search(api, query)
else:
interactive_mode(api)
if __name__ == "__main__":
main()