mincomp commited on
Commit
7f345a2
·
verified ·
1 Parent(s): ffb4def

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. main.py +692 -0
main.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ from functools import wraps
5
+
6
+ import chromadb
7
+ import gradio as gr
8
+ from openai import OpenAI
9
+ from opensearchpy import OpenSearch
10
+ from sentence_transformers import SentenceTransformer
11
+
12
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
13
+
14
+
15
+ def debounce(wait):
16
+ def decorator(fn):
17
+ last_call = 0
18
+
19
+ @wraps(fn)
20
+ def debounced(*args, **kwargs):
21
+ nonlocal last_call
22
+ now = time.time()
23
+ if now - last_call >= wait:
24
+ last_call = now
25
+ return fn(*args, **kwargs)
26
+
27
+ return debounced
28
+
29
+ return decorator
30
+
31
+
32
+ VECTOR_DB = os.getenv("VECTOR_DB", "chroma")
33
+ MODEL = os.getenv("MODEL", "gpt-4o-mini")
34
+
35
+ TOP_K = 10
36
+ host = "localhost"
37
+ port = 9200
38
+ OPENSEARCH_ADMIN_PASSWORD = os.getenv("OPENSEARCH_ADMIN_PASSWORD", "yw7L5u9nLs3a")
39
+ auth = (
40
+ "admin",
41
+ OPENSEARCH_ADMIN_PASSWORD,
42
+ ) # For testing only. Don't store credentials in code.
43
+
44
+ chroma_client = chromadb.Client()
45
+
46
+ # Create the client with SSL/TLS enabled, but hostname verification disabled.
47
+ os_client = OpenSearch(
48
+ hosts=[{"host": host, "port": port}],
49
+ http_compress=True, # enables gzip compression for request bodies
50
+ http_auth=auth,
51
+ use_ssl=True,
52
+ verify_certs=False,
53
+ ssl_assert_hostname=False,
54
+ ssl_show_warn=False,
55
+ )
56
+
57
+ all_props = json.load(open("all_properties.json"))
58
+ props_core = [
59
+ {
60
+ "property": prop["property"],
61
+ "address": prop["address"],
62
+ "school": prop["school"],
63
+ "listPrice": prop["listPrice"],
64
+ }
65
+ for prop in all_props
66
+ ]
67
+
68
+ client = OpenAI(
69
+ # This is the default and can be omitted
70
+ api_key=os.environ.get("OPENAI_API_KEY"),
71
+ )
72
+
73
+
74
+ chat_history = []
75
+ current_properties = {}
76
+ user_criteria = []
77
+
78
+ scoring_prompt = """
79
+ # System Prompt: Real Estate Assistant with JSON Output
80
+
81
+ You are an AI assistant specializing in real estate. Your role is to handle three types of inputs:
82
+ 1. General questions about properties or real estate from users.
83
+ 2. Comments about the user's criteria for properties.
84
+ 3. A JSON list of properties from another system.
85
+
86
+ For all types of interactions, your output should always be in JSON format.
87
+
88
+ ## Input Types:
89
+ 1. General question: A string containing a question about real estate or properties.
90
+ 2. Criteria update: A string containing the user's comments about their property preferences.
91
+ 3. Property list: A JSON array of property objects.
92
+
93
+ ## Property Format:
94
+ Properties will be in the following JSON format:
95
+
96
+ {
97
+ "address": "Property Address",
98
+ "description": "Property Description with Highlights"
99
+ }
100
+
101
+ ## Your Tasks:
102
+ 1. Determine the type of input received.
103
+ 2. For general questions:
104
+ - Provide a clear, concise answer to the question.
105
+ 3. For criteria updates:
106
+ - Update your understanding of the user's preferences.
107
+ - Re-score all known properties based on the new criteria.
108
+ 4. For property lists:
109
+ - Update your list of known properties.
110
+ - Score each property based on the current understanding of user preferences.
111
+ - If no user preferences have been specified yet, use general desirability factors.
112
+
113
+ ## Output Format:
114
+ Your output should always be a JSON object with a "type" field indicating the type of response, and additional fields based on the type:
115
+
116
+ For general questions:
117
+ {
118
+ "type": "answer",
119
+ "content": "Your answer to the question"
120
+ }
121
+
122
+ For criteria updates and property lists:
123
+ {
124
+ "type": "scoring",
125
+ "updatedCriteria": "Brief summary of the current criteria (include this field for criteria updates only)",
126
+ "properties": [
127
+ {
128
+ "address": "Property Address",
129
+ "score": 0-100,
130
+ "explanation": "Brief explanation for the score with *highlighted* matching criteria"
131
+ },
132
+ // ... (more properties)
133
+ ]
134
+ }
135
+
136
+ ## Important Considerations:
137
+ - Ensure your entire output is valid JSON.
138
+ - For general questions, provide accurate and helpful information.
139
+ - For criteria updates and property lists:
140
+ - Always re-score all known properties.
141
+ - Focus on the unique features and highlights mentioned in the property descriptions.
142
+ - Be objective and consistent in your scoring across all properties.
143
+ - Consider both explicitly stated criteria and implied preferences.
144
+ - If no user preferences are known, use general desirability factors.
145
+ - In the explanation field, use double asterisks (**) to highlight words or phrases that directly match user criteria.
146
+ - Look through all user preferences across interactions.
147
+
148
+ ## Example Inputs and Outputs:
149
+
150
+ 1. General Question:
151
+ Input: "What factors should I consider when buying a vacation home?"
152
+
153
+ Output:
154
+ {
155
+ "type": "answer",
156
+ "content": "When buying a vacation home, consider: 1) Location (proximity to attractions and ease of access), 2) Rental potential if you plan to rent it out, 3) Maintenance costs and property management, 4) Local market conditions and potential for appreciation, 5) Climate and weather patterns, 6) Amenities and nearby services, 7) Security, especially if the home will be vacant for long periods, 8) Insurance costs, which may be higher for second homes, 9) Tax implications, and 10) Your long-term goals for the property."
157
+ }
158
+
159
+ 2. Criteria Update:
160
+ Input: "I'm interested in properties with a modern kitchen and energy-efficient features."
161
+
162
+ Output:
163
+ {
164
+ "type": "scoring",
165
+ "updatedCriteria": "Preference for modern kitchens and energy-efficient features",
166
+ "properties": [
167
+ {
168
+ "address": "123 Main St, Anytown, USA",
169
+ "score": 85,
170
+ "explanation": "This property has a recently updated kitchen, which likely includes **modern** features. While **energy efficiency** isn't explicitly mentioned, the recent updates suggest some improvements in this area."
171
+ },
172
+ {
173
+ "address": "456 Elm St, Somewhere, USA",
174
+ "score": 70,
175
+ "explanation": "The description mentions *modern* appliances, which may include an **updated kitchen**, but doesn't specifically highlight **energy efficiency** features."
176
+ }
177
+ ]
178
+ }
179
+
180
+ 3. Property List:
181
+ Input:
182
+ [
183
+ {
184
+ "address": "789 Oak Rd, Newtown, USA",
185
+ "description": "Eco-friendly home with solar panels and energy-efficient appliances. Gourmet kitchen with state-of-the-art equipment. Smart home features throughout."
186
+ },
187
+ {
188
+ "address": "101 Pine Ave, Greenville, USA",
189
+ "description": "Charming cottage with original features. Cozy kitchen with vintage appeal. Beautiful garden with mature trees."
190
+ }
191
+ ]
192
+
193
+ Output:
194
+ {
195
+ "type": "scoring",
196
+ "properties": [
197
+ {
198
+ "address": "789 Oak Rd, Newtown, USA",
199
+ "score": 95,
200
+ "explanation": "This property strongly matches the criteria with its **energy-efficient** features and **modern**, **gourmet kitchen**. The **state-of-the-art equipment** and smart home features are an added bonus."
201
+ },
202
+ {
203
+ "address": "101 Pine Ave, Greenville, USA",
204
+ "score": 60,
205
+ "explanation": "While charming, this property doesn't align well with the preferences for **modern kitchens** and **energy efficiency**. The vintage kitchen and lack of mentioned energy features lower its score."
206
+ }
207
+ ]
208
+ }
209
+
210
+ Remember, your goal is to provide helpful information or accurate property scoring based on the input received and all known information, always in a valid JSON format. Track and apply all user preferences across the interactions, and highlight matching criteria in explanations using double asterisks.
211
+ """
212
+
213
+ categorize_prompt = """
214
+ You are an AI assistant specializing in real estate. Your role is to help users find properties that match their criteria and answer general questions about real estate. You must always respond in JSON format with two fields: "type" and "content". Follow these guidelines:
215
+
216
+ 1. Determine if the user is asking a general question about real estate or specifying/updating their property search criteria.
217
+
218
+ 2. Always structure your response as a JSON object with two fields:
219
+ - "type": Indicate the type of user message. Use one of the following values:
220
+ * "general_question": For general real estate queries or if clarification is needed
221
+ * "search_criteria": For specifying or updating property search criteria
222
+ - "content": Provide your response here based on the type of message
223
+
224
+ 3. For general questions (type: "general_question"):
225
+ - Provide clear, concise answers based on your real estate knowledge in the "content" field.
226
+ - Offer additional relevant information if appropriate.
227
+ - If the question is outside your expertise, politely say so and suggest consulting a real estate professional.
228
+ - If the user's intent is unclear, use this type and ask for clarification in the "content" field.
229
+
230
+ 4. For property search criteria (type: "search_criteria"):
231
+ - Identify and summarize the specific criteria mentioned by the user (e.g., location, price range, number of bedrooms, etc.).
232
+ - Include only the criteria explicitly stated by the user.
233
+ - Do not ask questions or request additional information.
234
+ - Present the summary in a clear, concise manner in the "content" field.
235
+
236
+ 5. Always maintain a professional, helpful tone in your "content".
237
+
238
+ 6. Remember previous interactions within the conversation to provide context-aware responses.
239
+
240
+ 7. Be prepared to explain real estate terms or processes if the user seems unfamiliar with them.
241
+
242
+ 8. If the user mentions specific financial concerns, suggest they consult with a financial advisor for personalized advice.
243
+
244
+ 9. Respect privacy and do not ask for or store any personal identifying information.
245
+
246
+ Remember, your goal is to assist the user in their property search or answer their real estate questions to the best of your ability, while knowing when to defer to human experts for complex or specialized inquiries. Always output your response as a JSON object with "type" and "content" fields.
247
+
248
+ Examples:
249
+
250
+ Input: "What's a mortgage?"
251
+ Output:
252
+ {
253
+ "type": "general_question",
254
+ "content": "A mortgage is a loan used to purchase real estate, where the property serves as collateral. The borrower repays the loan with interest over a set period, typically 15 or 30 years."
255
+ }
256
+
257
+ Input: "I want a 2-bedroom condo in Miami under $300k"
258
+ Output:
259
+ {
260
+ "type": "search_criteria",
261
+ "content": "Updated search criteria: 1) Type: Condo, 2) 2-Bedrooms, 3) Location: Miami, 4) Max price: $300,000"
262
+ }
263
+ """
264
+
265
+
266
+ def format_house_markdown(house):
267
+ return f"""
268
+ Price: {"${:,.0f}".format(house["listingPrice"])}
269
+
270
+ Size: {house["squareFootage"]} sqft
271
+
272
+ Bedrooms: {house["bedrooms"]}
273
+
274
+ Bathrooms: {house["bathrooms"]}
275
+
276
+ Score: {house["score"]}
277
+
278
+ Explanation: {house["explanation"]}
279
+
280
+ Description: {house["publicDescription"]}
281
+ """
282
+
283
+
284
+ def get_search_results(beds, baths, min_size, max_size, min_price, max_price):
285
+ if VECTOR_DB == "opensearch":
286
+ conditions = [
287
+ {"range": {"listingPrice": {"gte": min_price, "lte": max_price}}},
288
+ {"range": {"squareFootage": {"gte": min_size, "lte": max_size}}},
289
+ ]
290
+ if beds:
291
+ conditions.append({"terms": {"bedrooms": beds}})
292
+ if baths:
293
+ conditions.append({"terms": {"bathrooms": baths}})
294
+ if user_criteria:
295
+ embedding = embedding_model.encode(" ".join(user_criteria)).tolist()
296
+ conditions.append(
297
+ {"knn": {"publicDescriptionKnn": {"vector": embedding, "k": TOP_K}}}
298
+ )
299
+
300
+ result = os_client.search(
301
+ index="datafiniti_props",
302
+ body={"size": TOP_K, "query": {"bool": {"must": conditions}}},
303
+ )
304
+ houses = [hit["_source"] for hit in result["hits"]["hits"]]
305
+ return houses
306
+ elif VECTOR_DB == "chroma":
307
+ collection = chroma_client.get_collection(name="datafiniti_properties")
308
+ query_text = ""
309
+ if user_criteria:
310
+ query_text = " ".join(user_criteria)
311
+
312
+ where_conditions = [
313
+ {
314
+ "listingPrice": {"$gte": min_price},
315
+ },
316
+ {
317
+ "listingPrice": {"$lte": max_price},
318
+ },
319
+ {
320
+ "squareFootage": {"$gte": min_size},
321
+ },
322
+ {
323
+ "squareFootage": {"$lte": max_size},
324
+ },
325
+ ]
326
+ if beds:
327
+ where_conditions.append({"bedrooms": {"$in": beds}})
328
+ if baths:
329
+ where_conditions.append({"bathrooms": {"$in": baths}})
330
+
331
+ results = collection.query(
332
+ query_texts=[query_text],
333
+ where={"$and": where_conditions},
334
+ n_results=TOP_K,
335
+ )
336
+ all_values = []
337
+ for metadata, document in zip(results["metadatas"][0], results["documents"][0]):
338
+ metadata["publicDescription"] = document
339
+ all_values.append(metadata)
340
+ return all_values
341
+ else:
342
+ with open("sunnyvale.json", "r") as f:
343
+ data = json.load(f)
344
+
345
+ def condition(house):
346
+ if beds:
347
+ if house["bedrooms"] not in beds:
348
+ return False
349
+ if baths:
350
+ if house["bathrooms"] not in baths:
351
+ return False
352
+ if (
353
+ house["listingPrice"] < min_price
354
+ or house["listingPrice"] > max_price
355
+ ):
356
+ return False
357
+ if (
358
+ house["squareFootage"] < min_size
359
+ or house["squareFootage"] > max_size
360
+ ):
361
+ return False
362
+ return True
363
+
364
+ data = list(filter(condition, data))
365
+ return data
366
+
367
+
368
+ def update_property_list_and_get_response(
369
+ beds, baths, min_size, max_size, min_price, max_price
370
+ ):
371
+ houses = get_search_results(
372
+ beds=beds,
373
+ baths=baths,
374
+ min_size=min_size,
375
+ max_size=max_size,
376
+ min_price=min_price,
377
+ max_price=max_price,
378
+ )
379
+ global current_properties
380
+ current_properties = dict([(house["address"], house) for house in houses])
381
+ print(
382
+ f"updating current properties to {[property['address'] for property in current_properties.values()]} due to filters change"
383
+ )
384
+
385
+ model_input = json.dumps(
386
+ [
387
+ {"address": house["address"], "description": house["publicDescription"]}
388
+ for house in houses
389
+ ]
390
+ )
391
+
392
+ output = get_scoring_output(
393
+ model_input,
394
+ )
395
+ print("updating properties details due to filter change")
396
+ update_property_details(output)
397
+ output_text = get_scoring_response_to_user(output)
398
+ return output_text
399
+
400
+
401
+ # @debounce(1)
402
+ def update_filters(
403
+ beds,
404
+ baths,
405
+ min_size,
406
+ max_size,
407
+ min_price,
408
+ max_price,
409
+ history,
410
+ ):
411
+ """
412
+ Triggered by filters and criteria change, update the list of properties, and re-score
413
+ """
414
+ output_text = update_property_list_and_get_response(
415
+ beds, baths, min_size, max_size, min_price, max_price
416
+ )
417
+ history.append(("Updated filters, recalculating recommendations...", output_text))
418
+ return history, str(time.time())
419
+
420
+
421
+ def update_property_details(output_str):
422
+ global current_properties
423
+
424
+ output = json.loads(output_str)
425
+ for property in output["properties"]:
426
+ address = property["address"]
427
+ current_properties[address]["score"] = property["score"]
428
+ current_properties[address]["explanation"] = property["explanation"]
429
+
430
+
431
+ def get_scoring_output(user_message):
432
+ """
433
+ Takes in message (could come from user, or ES search result), outputs LLM response
434
+ """
435
+ print(f"taking in message {user_message}")
436
+ messages = (
437
+ [
438
+ {
439
+ "role": "system",
440
+ "content": scoring_prompt,
441
+ },
442
+ ]
443
+ + [
444
+ {
445
+ "role": "user",
446
+ "content": criteria_update,
447
+ }
448
+ for criteria_update in user_criteria
449
+ ]
450
+ + [
451
+ {
452
+ "role": "user",
453
+ "content": user_message,
454
+ }
455
+ ]
456
+ )
457
+ print(f"sending {messages=}")
458
+ chat_completion = client.chat.completions.create(
459
+ messages=messages,
460
+ model=MODEL,
461
+ )
462
+ content = chat_completion.choices[0].message.content
463
+ print(f"model output: {content}")
464
+ chat_history.append(
465
+ {
466
+ "role": "user",
467
+ "content": user_message,
468
+ }
469
+ )
470
+ chat_history.append({"role": "assistant", "content": content})
471
+ return content
472
+
473
+
474
+ def get_scoring_response_to_user(message_str):
475
+ """
476
+ Parse model's message in JSON and return text to user
477
+ """
478
+ message = json.loads(message_str)
479
+ if message["type"] == "scoring":
480
+ if not message["properties"]:
481
+ return "Thank for providing your criteria, please update filters to see recommendations"
482
+
483
+ recommended_property = sorted(
484
+ message["properties"], key=lambda item: item["score"], reverse=True
485
+ )[0]
486
+ return f"""
487
+ Based on the criteria, I recommended {recommended_property["address"]}. {recommended_property["explanation"]}
488
+ """
489
+ else:
490
+ return message["content"]
491
+
492
+
493
+ def categorize_user_input(message):
494
+ """
495
+ Categorize user input as general question or search criteria
496
+ """
497
+ messages = (
498
+ [
499
+ {
500
+ "role": "system",
501
+ "content": categorize_prompt,
502
+ }
503
+ ]
504
+ + chat_history
505
+ + [
506
+ {
507
+ "role": "user",
508
+ "content": message,
509
+ },
510
+ ]
511
+ )
512
+ chat_completion = client.chat.completions.create(
513
+ messages=messages,
514
+ model=MODEL,
515
+ )
516
+ content = chat_completion.choices[0].message.content
517
+ # no need to store this in chat history
518
+ return content
519
+
520
+
521
+ def process_user_input(
522
+ message,
523
+ history,
524
+ beds,
525
+ baths,
526
+ min_size,
527
+ max_size,
528
+ min_price,
529
+ max_price,
530
+ ):
531
+ categorization_str = categorize_user_input(message)
532
+ categorization = json.loads(categorization_str)
533
+ if categorization["type"] == "general_question":
534
+ response_text = categorization["content"]
535
+ else:
536
+ global user_criteria
537
+ user_criteria.append(message)
538
+ print(f"appending user criteria {user_criteria}")
539
+ response_text = update_property_list_and_get_response(
540
+ beds, baths, min_size, max_size, min_price, max_price
541
+ )
542
+ history.append((message, response_text))
543
+ return "", history, str(time.time())
544
+
545
+
546
+ # Create Gradio Interface
547
+ with gr.Blocks() as demo:
548
+ label_trigger = gr.Label("", visible=False)
549
+ version = gr.Label("Build 09032024")
550
+ # Top Section with a Textbox and a Slider
551
+ with gr.Column():
552
+ beds = gr.CheckboxGroup([1, 2, 3, 4, 5], label="Beds")
553
+ baths = gr.CheckboxGroup([1, 2, 3, 4, 5], label="Baths")
554
+ min_size_slider = gr.Slider(
555
+ label="Minimal Size Sqft",
556
+ value=0,
557
+ minimum=0,
558
+ maximum=5000,
559
+ step=100,
560
+ )
561
+ max_size_slider = gr.Slider(
562
+ label="Maximal Size Sqft",
563
+ value=10000,
564
+ minimum=0,
565
+ maximum=5000,
566
+ step=100,
567
+ )
568
+ min_price_slider = gr.Slider(
569
+ label="Minimal Price $",
570
+ value=0,
571
+ minimum=0,
572
+ maximum=10000000,
573
+ step=10000,
574
+ )
575
+ max_price_slider = gr.Slider(
576
+ label="Maximal Price $",
577
+ value=10000000,
578
+ minimum=0,
579
+ maximum=10000000,
580
+ step=10000,
581
+ )
582
+ all_filters = [
583
+ beds,
584
+ baths,
585
+ min_size_slider,
586
+ max_size_slider,
587
+ min_price_slider,
588
+ max_price_slider,
589
+ ]
590
+
591
+ # Bottom Section with ChatInterface and Canvas
592
+ with gr.Row():
593
+ with gr.Column():
594
+ chat_interface = gr.Chatbot(label="Chat Interface", elem_id="chat")
595
+ msg = gr.Textbox()
596
+
597
+ @gr.render(triggers=[label_trigger.change])
598
+ def show_accordions():
599
+ if not current_properties:
600
+ return
601
+ sorted_properties = sorted(
602
+ list(current_properties.values()),
603
+ key=lambda item: item["score"],
604
+ reverse=True,
605
+ )
606
+ highest_score = sorted_properties[0]["score"]
607
+ with gr.Column():
608
+ for property in sorted_properties:
609
+ with gr.Accordion(
610
+ f'{property["address"]} {"${:,.0f}".format(property["listingPrice"])} {property["squareFootage"]} sqft {property["bedrooms"]}bed{property["bathrooms"]}bath',
611
+ open=True if property["score"] == highest_score else False,
612
+ ):
613
+ gr.Markdown(value=format_house_markdown(property))
614
+
615
+ msg.submit(
616
+ process_user_input,
617
+ [msg, chat_interface] + all_filters,
618
+ [msg, chat_interface, label_trigger],
619
+ )
620
+
621
+ for item in all_filters:
622
+ if isinstance(item, gr.Slider):
623
+ item.release(
624
+ update_filters,
625
+ all_filters + [chat_interface],
626
+ [chat_interface, label_trigger],
627
+ )
628
+ else:
629
+ item.change(
630
+ update_filters,
631
+ all_filters + [chat_interface],
632
+ [chat_interface, label_trigger],
633
+ )
634
+
635
+
636
+ def load_data_to_chroma():
637
+ import chromadb
638
+
639
+ chroma_client = chromadb.Client()
640
+ try:
641
+ collection = chroma_client.create_collection(name="datafiniti_properties")
642
+ except:
643
+ print("data is already added, exit")
644
+ return
645
+
646
+ ids = []
647
+ documents = []
648
+ metadatas = []
649
+ with open("datafiniti_properties_sunnyvale_400.json", "r") as f:
650
+ for line in f:
651
+ property = json.loads(line)
652
+ try:
653
+ print(f'indexing {property["address"]}')
654
+ bathrooms = int(property["numBathroom"])
655
+ beds = property["numBedroom"]
656
+ price = property["mostRecentPriceAmount"]
657
+ size = property["floorSizeValue"]
658
+ address = ", ".join(
659
+ [
660
+ property["address"],
661
+ property["city"],
662
+ property["province"],
663
+ property["postalCode"][:5],
664
+ ]
665
+ )
666
+
667
+ descriptions = property["descriptions"]
668
+ descriptions = sorted(
669
+ descriptions, key=lambda x: x["dateSeen"], reverse=True
670
+ )
671
+ description = descriptions[0]["value"]
672
+
673
+ metadata = {
674
+ "bathrooms": bathrooms,
675
+ "bedrooms": beds,
676
+ "listingPrice": price,
677
+ "squareFootage": size,
678
+ "address": address,
679
+ }
680
+
681
+ ids.append(address)
682
+ documents.append(description)
683
+ metadatas.append(metadata)
684
+ except Exception as e:
685
+ print(e)
686
+ pass
687
+ collection.add(ids=ids, documents=documents, metadatas=metadatas)
688
+
689
+
690
+ load_data_to_chroma()
691
+ # Launch the Gradio Interface
692
+ demo.launch()