-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
355 lines (306 loc) · 15 KB
/
main.py
File metadata and controls
355 lines (306 loc) · 15 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import os
import json
import time
import secrets
import gradio as gr
from dotenv import load_dotenv
from pathlib import Path
from postcode_eu_api_client import Client
load_dotenv()
api_key = os.getenv('POSTCODE_EU_API_KEY')
api_secret = os.getenv('POSTCODE_EU_API_SECRET')
if not api_key or not api_secret:
raise ValueError('Please set POSTCODE_EU_API_KEY and POSTCODE_EU_API_SECRET in your .env file')
client = Client(api_key, api_secret, 'API Method Explorer (Python module example)')
def get_supported_countries():
cache_path = Path(__file__).parent / 'supported_countries_cache.json'
if cache_path.exists():
try:
with open(cache_path, 'r') as f:
cache_data = json.load(f)
if time.time() - cache_data.get('timestamp', 0) < 86400: # Cache for a day.
return cache_data['countries']
except (json.JSONDecodeError, KeyError):
pass
try:
response = client.international_get_supported_countries()
cache_data = {'timestamp': time.time(), 'countries': response}
with open(cache_path, 'w') as f:
json.dump(cache_data, f)
return response
except Exception as e:
print(f"Failed to fetch countries from API: {e}")
return []
def get_session_id():
return secrets.token_hex(16) # 16 bytes for 32 hex characters.
# Get supported countries for dropdown choices
country_choices = [(country['name'], country['iso3']) for country in get_supported_countries()]
initial_context = country_choices[0][1]
with gr.Blocks() as demo:
gr.Markdown('# API Methods Explorer')
with gr.Row():
with gr.Column():
with gr.Accordion('Autocomplete address', open=True):
gr.Markdown(client.international_autocomplete.__doc__)
gr.Markdown(client.international_get_details.__doc__)
autocomplete_country_dropdown = gr.Dropdown(choices=country_choices, label='Country')
autocomplete_context_input = gr.Textbox(label='Context', interactive=False, value=initial_context)
autocomplete_term_input = gr.Textbox(label='Term', placeholder='City, street or postcode')
autocomplete_matches_dataset = gr.Dataset(
visible=False,
label='Matches',
components=[autocomplete_term_input]
)
autocomplete_reset_btn = gr.Button('Clear')
autocomplete_session = gr.State(get_session_id())
current_autocomplete_match = gr.State(None)
with gr.Accordion('Validate address', open=False):
gr.Markdown(client.validate.__doc__)
validate_inputs = [
gr.Dropdown(choices=country_choices, label='Country'),
gr.Textbox(label='Postcode'),
gr.Textbox(label='Locality'),
gr.Textbox(label='Street'),
gr.Textbox(label='Building'),
gr.Textbox(label='Region'),
gr.Textbox(label='Street and Building'),
]
validate_btn = gr.Button('Validate', variant='primary')
gr.ClearButton(validate_inputs[1:])
gr.Examples(
example_labels=["Correct typo's", 'Ambiguous matches', 'Valid address'],
examples=[
['BEL', '2000', 'antwerpn', 'leystraat', '11', '', ''],
['NLD', '', 'Winsum', 'Postbus', '1', '', ''],
['NOR', '0150', 'Oslo', '', '', '', 'Kirsten Flagstads plass 1'],
],
inputs=validate_inputs,
)
with gr.Accordion('Get supported countries', open=False):
gr.Markdown(client.international_get_supported_countries.__doc__)
get_countries_btn = gr.Button('Get countries', variant='primary')
with gr.Accordion('Get country information', open=False):
country_input = gr.Textbox(label='Country name or ISO code')
get_country_btn = gr.Button('Lookup', variant='primary')
with gr.Accordion('Dutch address lookup', open=False):
gr.Markdown(client.dutch_address_by_postcode.__doc__)
postcode_input = gr.Textbox(label='Postcode', placeholder='e.g., 1234AB')
house_number_input = gr.Textbox(label='House number')
house_number_addition_input = gr.Textbox(label='House number addition')
dutch_address_lookup_btn = gr.Button('Lookup', variant='primary')
gr.ClearButton([postcode_input, house_number_input, house_number_addition_input])
gr.Examples(
example_labels=['Valid combination', 'Invalid combination', 'Invalid addition', 'PO box'],
examples=[['2012ES', '30', ''], ['1064DG', '99', ''], ['2161AM', '166', 'b'], ['1000AA', '1', '']],
inputs=[postcode_input, house_number_input, house_number_addition_input],
)
with gr.Accordion('Dutch address RD (Rijksdriehoeksmeting)', open=False):
gr.Markdown(client.dutch_address_rd.__doc__)
rd_x_input = gr.Number(label='RD X')
rd_y_input = gr.Number(label='RD Y')
dutch_rd_lookup_btn = gr.Button('Lookup', variant='primary')
gr.Examples(
examples=[[103242, 487716], [97834, 475879], [153770, 407977]],
inputs=[rd_x_input, rd_y_input],
)
with gr.Accordion('Dutch address latitude and longitude', open=False):
gr.Markdown(client.dutch_address_lat_lon.__doc__)
latitude_input = gr.Number(label='Latitude')
longitude_input = gr.Number(label='Longitude')
dutch_latlon_lookup_btn = gr.Button('Lookup', variant='primary')
gr.Examples(
examples=[[52.37487801, 4.62714526], [52.26796661, 4.54973345], [51.66061536, 5.3694383]],
inputs=[latitude_input, longitude_input],
)
with gr.Accordion('Dutch address BAG number designation', open=False):
gr.Markdown(client.dutch_address_bag_number_designation.__doc__)
bag_number_designation_id_input = gr.Textbox(label='BAG Number Designation ID (Nummeraanduiding ID)')
bag_number_designation_lookup_btn = gr.Button('Lookup', variant='primary')
gr.Examples(
examples=[['0392200000029398'], ['0553200000012529'], ['0845200000006831']],
inputs=[bag_number_designation_id_input],
)
with gr.Accordion('Dutch address BAG addressable object', open=False):
gr.Markdown(client.dutch_address_bag_addressable_object.__doc__)
bag_addressable_object_id_input = gr.Textbox(label='BAG Addressable Object ID (Adresseerbaar object ID) ')
bag_addressable_object_lookup_btn = gr.Button('Lookup', variant='primary')
gr.Examples(
examples=[['0392010000029398'], ['0553010000012483'], ['0845010000001763']],
inputs=[bag_addressable_object_id_input],
)
with gr.Accordion('Dutch address postcode ranges', open=False):
gr.Markdown(client.dutch_address_postcode_ranges.__doc__)
postcode_ranges_postcode_input = gr.Textbox(label='Postcode', placeholder='e.g., 1234AB')
postcode_ranges_lookup_btn = gr.Button('Lookup', variant='primary')
gr.Examples(
examples=[['5271XD'], ['2161AM'], ['2011VM'], ['1097DN']],
inputs=[postcode_ranges_postcode_input],
)
with gr.Accordion('Account info', open=False):
gr.Markdown(client.account_info.__doc__)
account_info_btn = gr.Button('Get account info', variant='primary')
with gr.Accordion('Create client account (resellers only)', open=False):
gr.Markdown(client.create_client_account.__doc__)
create_client_account_inputs = [
gr.Textbox(label='Company Name'),
gr.Textbox(label='Country ISO', placeholder='NLD', info='ISO 3 country code'),
gr.Textbox(label='VAT Number', info='Required for EU member country other than the Netherlands.'),
gr.Textbox(label='Contact Email'),
gr.Dropdown(
choices=[0, 50, 100, 250, 500, 1000],
label='Subscription Amount',
value=0,
info='Specify 0 to create a test account without a subscription.'
),
gr.Textbox(label='Site URLs (comma separated)', placeholder='example.com, test.example.com'),
gr.Textbox(label='Invoice Email'),
gr.Textbox(label='Invoice Reference (optional)'),
gr.Textbox(label='Invoice Address Line 1'),
gr.Textbox(label='Invoice Address Line 2 (optional)'),
gr.Textbox(label='Invoice Address Postal Code'),
gr.Textbox(label='Invoice Address Locality'),
gr.Textbox(label='Invoice Address Region (optional)'),
gr.Textbox(label='Invoice Address Country ISO', placeholder='NLD', info='ISO 3 country code'),
gr.Textbox(label='Invoice Contact Name (optional)')
]
create_client_account_btn = gr.Button('Create account', variant='primary')
gr.Markdown('**NB: in this example you will receive a dummy response, instead of actually creating an account**.')
gr.Examples(
example_labels=['Example company'],
examples=[
[
'Example company',
'NLD',
'',
'info@example.com',
0,
'example.com',
'billing@example.com',
'Example ref',
'Postbus 1',
'',
'1000',
'Amsterdam',
'',
'NLD',
'Test bob'
]
],
inputs=create_client_account_inputs
)
with gr.Column():
api_response_json = gr.JSON(label='Result', max_height=None, open=True)
def select_autocomplete_country(country):
return get_session_id(), country, None
autocomplete_country_dropdown.change(
fn=select_autocomplete_country,
inputs=autocomplete_country_dropdown,
outputs=[autocomplete_session, autocomplete_context_input, autocomplete_term_input],
show_progress='hidden'
)
def get_autocomplete_matches(country, context, term, session, current_match):
if not term:
return gr.Dataset(visible=False), country, get_session_id(), None, {}
if current_match and current_match['precision'] == 'Address':
response = client.international_get_details(context, session)
return gr.Dataset(), context, session, None, response
response = client.international_autocomplete(context, term, session)
context = response['newContext'] or context # Forced switch away from current context - current context no longer valid given user input.
labels = [
f"{m['label']} - {m['description']}" if m['description'] else m['label']
for m in response['matches']
]
return gr.Dataset(visible=True, samples=response['matches'], sample_labels=labels), context, session, None, response
autocomplete_term_input.change(
fn=get_autocomplete_matches,
inputs=[
autocomplete_country_dropdown,
autocomplete_context_input,
autocomplete_term_input,
autocomplete_session,
current_autocomplete_match
],
outputs=[
autocomplete_matches_dataset,
autocomplete_context_input,
autocomplete_session,
current_autocomplete_match,
api_response_json
],
show_progress='minimal',
show_progress_on=api_response_json
)
def select_autocomplete_match(match):
return match, match['context'], match['value']
autocomplete_matches_dataset.click(
fn=select_autocomplete_match,
inputs=[autocomplete_matches_dataset],
outputs=[current_autocomplete_match, autocomplete_context_input, autocomplete_term_input],
show_progress='minimal',
show_progress_on=api_response_json
)
def reset_autocomplete(country):
return country, None, {}
autocomplete_reset_btn.click(
fn=reset_autocomplete,
inputs=autocomplete_country_dropdown,
outputs=[autocomplete_context_input, autocomplete_term_input, api_response_json],
show_progress='hidden'
)
validate_btn.click(
fn=client.validate,
inputs=validate_inputs,
outputs=api_response_json
)
get_countries_btn.click(
fn=client.international_get_supported_countries,
inputs=[],
outputs=api_response_json
)
get_country_btn.click(
fn=client.get_country,
inputs=country_input,
outputs=api_response_json
)
dutch_address_lookup_btn.click(
fn=client.dutch_address_by_postcode,
inputs=[postcode_input, house_number_input, house_number_addition_input],
outputs=api_response_json
)
dutch_rd_lookup_btn.click(
fn=client.dutch_address_rd,
inputs=[rd_x_input, rd_y_input],
outputs=api_response_json
)
dutch_latlon_lookup_btn.click(
fn=client.dutch_address_lat_lon,
inputs=[latitude_input, longitude_input],
outputs=api_response_json
)
bag_number_designation_lookup_btn.click(
fn=client.dutch_address_bag_number_designation,
inputs=bag_number_designation_id_input,
outputs=api_response_json
)
bag_addressable_object_lookup_btn.click(
fn=client.dutch_address_bag_addressable_object,
inputs=bag_addressable_object_id_input,
outputs=api_response_json
)
postcode_ranges_lookup_btn.click(
fn=client.dutch_address_postcode_ranges,
inputs=postcode_ranges_postcode_input,
outputs=api_response_json
)
account_info_btn.click(
fn=client.account_info,
outputs=api_response_json
)
def create_client_account_dummy(*args):
return client.create_client_account(*args, is_test=True)
create_client_account_btn.click(
fn=create_client_account_dummy,
inputs=create_client_account_inputs,
outputs=api_response_json,
)
demo.launch()