-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2086 lines (1742 loc) · 91.9 KB
/
app.py
File metadata and controls
2086 lines (1742 loc) · 91.9 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import re
import json
import os
from itertools import islice
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_openai import ChatOpenAI
from retailers import get_product_links, check_disc_tree_stock
from flight_chart import generate_flight_path, get_flight_stats, FLIGHT_NUMBER_GUIDE, calculate_arm_speed_factor
from knowledge_base import DiscGolfKnowledgeBase
from feedback_system import FeedbackSystem
# --- CONFIGURATION ---
st.set_page_config(page_title="FindMinDisc", page_icon="🥏")
# --- CONSTANTS ---
# Pattern keywords for detecting "tell me more" requests
TELL_MORE_PATTERNS = ['fortæl', 'forklar', 'mere om', 'beskriv', 'info om', 'information om']
# Popular discs prioritized in recommendations (based on Reddit discussions and community feedback)
POPULAR_DISCS = [
# Distance drivers
'Destroyer', 'Wraith', 'Thunderbird', 'Firebird', 'Shryke', 'Tern',
# Fairway drivers
'Escape', 'Leopard', 'Leopard3', 'Roadrunner', 'Valkyrie', 'Volt', 'Tesla', 'Teebird', 'Teebird3',
# Midrange
'Buzzz', 'Roc3', 'Roc', 'Mako3', 'Hex', 'Compass', 'Emac Truth', 'Origin',
# Putters
'Aviar', 'Luna', 'Judge', 'P2', 'Envy', 'Berg', 'Maiden',
# MVP/Axiom popular
'Photon', 'Wave', 'Insanity', 'Relay', 'Crave',
]
def parse_flight_chart_request(prompt):
"""
Parse natural language requests for flight charts.
Examples:
- "Vis mig flight charts for Destroyer, Mamba og Zone SS"
- "Sammenlign Buzzz og Roc3"
- "Flight chart for Firebird"
- "Destroyer vs Wraith"
- "Tilføj Wraith" (adds to existing)
- "Begynder niveau" / "Pro niveau" (changes level)
Returns dict with 'discs' list and 'arm_speed'
"""
prompt_lower = prompt.lower()
# Check if this is a "tell me more" request first (takes priority over flight charts)
is_tell_more = any(p in prompt_lower for p in TELL_MORE_PATTERNS)
# If it's a "tell me more" request, don't treat it as a chart request
if is_tell_more:
return {'is_chart_request': False}
# Check if this is a flight chart request
flight_keywords = ['flight chart', 'flightchart', 'sammenlign', 'compare', 'vis mig', 'show me', 'chart for', ' vs ', ' mod ']
is_chart_request = any(kw in prompt_lower for kw in flight_keywords)
# Check if this is an "add to existing" request
add_keywords = ['tilføj', 'også', 'add', 'inkluder', 'plus', 'og også', 'hvad med']
is_add_request = any(kw in prompt_lower for kw in add_keywords)
# Check for arm speed change
arm_speed = None
if 'begynder' in prompt_lower or 'slow' in prompt_lower or 'langsom' in prompt_lower:
arm_speed = 'slow'
elif 'pro' in prompt_lower or 'fast' in prompt_lower or 'hurtig' in prompt_lower:
arm_speed = 'fast'
elif 'øvet' in prompt_lower or 'normal' in prompt_lower or 'mellem' in prompt_lower:
arm_speed = 'normal'
# Find disc names - try exact match first, then fuzzy match
disc_names_sorted = sorted(DISC_DATABASE.keys(), key=len, reverse=True)
# Create normalized lookup: "aviar3" -> "Aviar 3", "teebird3" -> "Teebird 3"
normalized_lookup = {}
for disc_name in disc_names_sorted:
# Normalize: lowercase, remove spaces and hyphens
normalized = disc_name.lower().replace(' ', '').replace('-', '')
normalized_lookup[normalized] = disc_name
disc_names_found = []
prompt_remaining = prompt_lower
prompt_normalized = prompt_lower.replace(' ', '').replace('-', '')
# First try exact matches (with word boundaries)
for disc_name in disc_names_sorted:
disc_lower = disc_name.lower()
pattern = r'(?:^|[^a-zæøå0-9])' + re.escape(disc_lower) + r'(?:[^a-zæøå0-9]|$)'
if re.search(pattern, prompt_remaining):
disc_names_found.append(disc_name)
prompt_remaining = re.sub(pattern, ' ', prompt_remaining, count=1)
# Also remove from normalized
prompt_normalized = prompt_normalized.replace(disc_lower.replace(' ', '').replace('-', ''), '', 1)
# Then try normalized matches (handles "Aviar3" -> "Aviar 3")
for normalized, disc_name in sorted(normalized_lookup.items(), key=lambda x: len(x[0]), reverse=True):
if disc_name in disc_names_found:
continue # Already found
if normalized in prompt_normalized:
disc_names_found.append(disc_name)
prompt_normalized = prompt_normalized.replace(normalized, '', 1)
# Only treat as chart request if:
# - 2+ discs found (comparison), OR
# - chart keywords + at least 1 disc, OR
# - add keywords + at least 1 disc
# Note: arm_speed alone is NOT enough - we handle that in the chat handler
if len(disc_names_found) >= 2 or (is_chart_request and disc_names_found) or (is_add_request and disc_names_found):
return {
'discs': disc_names_found,
'arm_speed': arm_speed,
'is_chart_request': True,
'is_add_request': is_add_request,
'is_speed_change': False
}
# Arm speed change only (no new discs) - let the handler check if there are existing discs
if arm_speed is not None:
return {
'discs': [],
'arm_speed': arm_speed,
'is_chart_request': False, # Not a chart request on its own
'is_add_request': False,
'is_speed_change': True
}
return {'is_chart_request': False}
def filter_wrong_speed_discs(response, database, min_speed, max_speed):
"""
Remove disc recommendations that don't match the requested speed range.
Returns the filtered response.
"""
lines = response.split('\n')
result_lines = []
skip_until_next_section = False
current_disc = None
current_disc_speed = None
section_start_idx = -1
for i, line in enumerate(lines):
# Check if this line starts a new disc section
disc_found = None
for disc_name in sorted(database.keys(), key=len, reverse=True):
if re.search(rf'\*\*\s*{re.escape(disc_name)}\s*\*\*|###.*{re.escape(disc_name)}|\[\s*{re.escape(disc_name)}\s*\]', line, re.IGNORECASE):
disc_found = disc_name
break
if disc_found:
# Check if the previous disc was out of range
if skip_until_next_section and section_start_idx >= 0:
# Remove the previous section (it was out of range)
result_lines = result_lines[:section_start_idx]
# Also add a note about why it was removed
current_disc = disc_found
disc_data = database.get(current_disc, {})
current_disc_speed = disc_data.get('speed', 0)
section_start_idx = len(result_lines)
# Check if this disc is outside the speed range
if current_disc_speed < min_speed or current_disc_speed > max_speed:
skip_until_next_section = True
continue # Don't add this line
else:
skip_until_next_section = False
if skip_until_next_section:
continue # Skip lines in wrong-speed sections
result_lines.append(line)
# Clean up any trailing empty lines from removed sections
while result_lines and result_lines[-1].strip() == '':
result_lines.pop()
return '\n'.join(result_lines)
def fix_flight_numbers_in_response(response, database):
"""
Post-process AI response to fix any incorrect flight numbers.
The AI often hallucinates flight numbers from its training data.
This function forces the correct values from our database.
"""
# Split response into sections by headers (lines starting with ** or ###)
lines = response.split('\n')
current_disc = None
result_lines = []
for line in lines:
# Check if this line defines a new disc (bold name or header)
disc_found = None
for disc_name in sorted(database.keys(), key=len, reverse=True):
# Check for **DiscName** or ### DiscName patterns
if re.search(rf'\*\*\s*{re.escape(disc_name)}\s*\*\*|###.*{re.escape(disc_name)}', line, re.IGNORECASE):
disc_found = disc_name
break
# Also check for just the disc name at start of line (like "Photon")
elif re.match(rf'^[\*\s]*{re.escape(disc_name)}\s*$', line.strip(), re.IGNORECASE):
disc_found = disc_name
break
if disc_found:
current_disc = disc_found
# If we're in a disc section, fix flight numbers on this line
if current_disc and current_disc in database:
disc_data = database[current_disc]
speed = str(disc_data.get('speed', 0))
glide = str(disc_data.get('glide', 0))
turn = str(disc_data.get('turn', 0))
fade = str(disc_data.get('fade', 0))
# Fix Flight: X/X/X/X format
line = re.sub(
r'(Flight[:\s]+)\d+/\d+/-?\d+\.?\d*/\d+\.?\d*',
rf'\g<1>{speed}/{glide}/{turn}/{fade}',
line, flags=re.IGNORECASE
)
# Fix individual values
line = re.sub(r'(Speed[:\s]+)\d+', rf'\g<1>{speed}', line, flags=re.IGNORECASE)
line = re.sub(r'(Glide[:\s]+)\d+', rf'\g<1>{glide}', line, flags=re.IGNORECASE)
line = re.sub(r'(Turn[:\s]+)-?\d+\.?\d*', rf'\g<1>{turn}', line, flags=re.IGNORECASE)
line = re.sub(r'(Fade[:\s]+)\d+\.?\d*', rf'\g<1>{fade}', line, flags=re.IGNORECASE)
result_lines.append(line)
return '\n'.join(result_lines)
def fix_manufacturer_names_in_response(response, database):
"""
Post-process AI response to fix any incorrect manufacturer names.
The AI sometimes hallucinates wrong manufacturers (e.g. "Dynamic Discs Diamond"
when Diamond is actually by Latitude 64).
"""
result = response
# Find all disc names mentioned in the response
for disc_name in sorted(database.keys(), key=len, reverse=True):
if disc_name in database:
correct_manufacturer = database[disc_name].get('manufacturer', '')
if not correct_manufacturer:
continue
# Pattern 1: Fix "### **WrongManufacturer DiscName** af WrongManufacturer"
# This handles the full line with both wrong prefix and suffix
pattern1 = rf'(###\s*\*\*)[^*\n]*?{re.escape(disc_name)}\s*\*\*(\s+af\s+)[A-Za-z0-9\s]+?(?=\n|$|-)'
if re.search(pattern1, result, re.IGNORECASE):
result = re.sub(pattern1, rf'\g<1>{disc_name}**\g<2>{correct_manufacturer}', result, flags=re.IGNORECASE)
# Pattern 2: Fix just "**DiscName** af WrongManufacturer" (no prefix issue)
pattern2 = rf'(\*\*{re.escape(disc_name)}\*\*\s+af\s+)[A-Za-z0-9\s]+?(?=\n|$|-)'
if re.search(pattern2, result, re.IGNORECASE):
result = re.sub(pattern2, rf'\g<1>{correct_manufacturer}', result, flags=re.IGNORECASE)
return result
def handle_free_form_question(prompt, user_prefs=None):
"""
Handle any free-form disc golf question using AI + web search.
Returns AI response with disc recommendations.
"""
if user_prefs is None:
user_prefs = {}
# Extract useful info from the prompt
prompt_lower = prompt.lower()
# ==== HANDLE "TELL ME MORE" QUESTIONS ====
# Detect questions like "fortæl mig mere om dem", "mere om Volt"
is_tell_more = any(p in prompt_lower for p in TELL_MORE_PATTERNS)
# Find which discs the user is asking about
discs_in_prompt = []
for disc_name in sorted(DISC_DATABASE.keys(), key=len, reverse=True):
if disc_name.lower() in prompt_lower:
discs_in_prompt.append(disc_name)
if len(discs_in_prompt) >= 4:
break
# If "dem" (them) is mentioned but no disc names, use shown_discs
shown_disc_names = user_prefs.get('shown_discs', [])
if is_tell_more and not discs_in_prompt and ('dem' in prompt_lower or 'disse' in prompt_lower or 'de ' in prompt_lower):
discs_in_prompt = shown_disc_names
# If this is a "tell me more" question with specific discs, generate direct response
if is_tell_more and discs_in_prompt:
response_parts = ["Selvfølgelig! Her er mere information om de valgte discs:\n"]
for disc_name in discs_in_prompt:
if disc_name in DISC_DATABASE:
data = DISC_DATABASE[disc_name]
speed = data.get('speed', 0)
glide = data.get('glide', 0)
turn = data.get('turn', 0)
fade = data.get('fade', 0)
manufacturer = data.get('manufacturer', 'Ukendt')
disc_type = data.get('disc_type', 'Disc')
stability = data.get('stability', '')
response_parts.append(f"### **{disc_name}** af {manufacturer}")
response_parts.append(f"- **Type:** {disc_type}")
response_parts.append(f"- **Flight:** {speed}/{glide}/{turn}/{fade}")
# Add description based on flight numbers
if turn <= -3:
turn_desc = "Meget understabil - drejer meget til højre for højrehåndede"
elif turn <= -1:
turn_desc = "Understabil - mild drejning til højre"
elif turn == 0:
turn_desc = "Neutral - flyver lige"
else:
turn_desc = "Stabil - modstår turn"
if fade >= 3:
fade_desc = "Hård fade - kraftig venstredrejning til sidst"
elif fade >= 2:
fade_desc = "Medium fade"
else:
fade_desc = "Blød fade - lander lige"
response_parts.append(f"- **Turn:** {turn_desc}")
response_parts.append(f"- **Fade:** {fade_desc}")
# Skill recommendation
if speed <= 7 and turn <= -1:
skill_rec = "God for begyndere og øvede"
elif speed >= 11:
skill_rec = "Kræver god armhastighed (erfarne spillere)"
else:
skill_rec = "Passer til de fleste spillere"
response_parts.append(f"- **Anbefales til:** {skill_rec}")
response_parts.append("") # Empty line between discs
response_parts.append("Vil du se en sammenligning af hvordan de flyver (flight chart)?")
return {
'response': '\n'.join(response_parts),
'disc_names': discs_in_prompt,
'skill_level': user_prefs.get('skill_level', 'intermediate'),
'max_dist': user_prefs.get('max_dist', 80),
'disc_type': None
}
# Try to detect disc type from question
disc_type = None
if 'putter' in prompt_lower:
disc_type = "Putter"
elif 'approach' in prompt_lower:
disc_type = "Putter" # Approach discs are typically putters/slow midranges
elif 'midrange' in prompt_lower or 'mid-range' in prompt_lower:
disc_type = "Midrange"
elif 'fairway' in prompt_lower:
disc_type = "Fairway driver"
elif 'distance' in prompt_lower or 'driver' in prompt_lower:
disc_type = "Distance driver"
# Try to detect explicit speed range (e.g., "7-9 speed", "speed 7-9")
speed_range_match = re.search(r'(\d+)\s*-\s*(\d+)\s*speed|speed\s*(\d+)\s*-\s*(\d+)', prompt_lower)
custom_speed_range = None
if speed_range_match:
groups = speed_range_match.groups()
min_speed = int(groups[0] or groups[2])
max_speed = int(groups[1] or groups[3])
custom_speed_range = (min_speed, max_speed)
# Also infer disc_type from speed range if not already set
if not disc_type:
if max_speed <= 3:
disc_type = "Putter"
elif max_speed <= 6:
disc_type = "Midrange"
elif max_speed <= 9:
disc_type = "Fairway driver"
else:
disc_type = "Distance driver"
# Try to detect skill level - None if not specified
skill_level = None
skill_specified = False
if 'nybegynder' in prompt_lower or 'begynder' in prompt_lower or 'ny ' in prompt_lower or 'starter' in prompt_lower or 'dårlig' in prompt_lower:
skill_level = "beginner"
skill_specified = True
elif 'øvet' in prompt_lower or 'intermediate' in prompt_lower:
skill_level = "intermediate"
skill_specified = True
elif 'erfaren' in prompt_lower or 'pro' in prompt_lower or 'avanceret' in prompt_lower or 'god ' in prompt_lower:
skill_level = "advanced"
skill_specified = True
# Try to detect throwing distance
max_dist = user_prefs.get('max_dist', None)
dist_specified = max_dist is not None
numbers = re.findall(r'(\d+)\s*(?:m|meter)', prompt_lower)
if numbers:
max_dist = int(numbers[0])
dist_specified = True
# Set defaults if we need to give recommendations but info is missing
if max_dist is None:
max_dist = 70 if skill_level == "beginner" else 80
if skill_level is None:
skill_level = "intermediate"
# Build search query
search_terms = prompt.replace('?', '').replace('!', '')
if skill_level == "beginner":
search_query = f"best disc golf discs for beginners {search_terms}"
else:
search_query = f"disc golf recommendation {search_terms}"
# ==== KNOWLEDGE BASE CONTEXT ====
kb_context = ""
if kb_enabled and kb:
try:
kb_results = kb.get_context_for_query(prompt, max_results=3)
if kb_results and kb_results != "No relevant information found in knowledge base.":
kb_context = f"\n\nRELEVANTE REDDIT DISKUSSIONER:\n{kb_results}"
except Exception as e:
print(f"Error accessing knowledge base: {e}")
kb_context = ""
# Web search
try:
search_results = search.run(search_query)[:4000]
except Exception:
search_results = ""
# Get sample discs from database for context
# First, prioritize discs that are currently shown (from chart comparison)
sample_discs = []
shown_disc_names = user_prefs.get('shown_discs', [])
# Add shown discs first with EXACT flight numbers
if shown_disc_names:
sample_discs.append("DISCS BRUGEREN LIGE HAR SET (brug PRÆCIS disse flight numbers):")
for disc_name in shown_disc_names:
if disc_name in DISC_DATABASE:
data = DISC_DATABASE[disc_name]
speed = data.get('speed', 0)
glide = data.get('glide', 4)
turn = data.get('turn', 0)
fade = data.get('fade', 2)
sample_discs.append(f" • {disc_name} ({data.get('manufacturer', '?')}): {speed}/{glide}/{turn}/{fade}")
sample_discs.append("") # Empty line separator
# Then add other relevant discs, prioritizing popular/Reddit-recommended ones
sample_discs.append("ANDRE RELEVANTE DISCS:")
added_discs = set(shown_disc_names) # Track what we've already added
# First, add popular discs that match the criteria
for disc_name in POPULAR_DISCS:
if disc_name in added_discs:
continue
if disc_name not in DISC_DATABASE:
continue
data = DISC_DATABASE[disc_name]
speed = data.get('speed', 0)
# Filter by skill level
if skill_level == "beginner" and speed > 9:
continue
# Filter by custom speed range if specified
if custom_speed_range:
min_s, max_s = custom_speed_range
if not (min_s <= speed <= max_s):
continue
# Otherwise filter by disc type
elif disc_type:
speed_ranges = {"Putter": (1, 3), "Midrange": (4, 6), "Fairway driver": (7, 9), "Distance driver": (10, 14)}
min_s, max_s = speed_ranges.get(disc_type, (1, 14))
if not (min_s <= speed <= max_s):
continue
sample_discs.append(f" • {disc_name} ({data.get('manufacturer', '?')}): {speed}/{data.get('glide', 4)}/{data.get('turn', 0)}/{data.get('fade', 2)}")
added_discs.add(disc_name)
if len(sample_discs) >= 35:
break
# Then add other discs from database to fill up to 35 total
if len(sample_discs) < 35:
for name, data in islice(DISC_DATABASE.items(), 200):
if name in added_discs:
continue # Skip discs already added
speed = data.get('speed', 0)
# Filter by skill level
if skill_level == "beginner" and speed > 9:
continue
# Filter by custom speed range if specified
if custom_speed_range:
min_s, max_s = custom_speed_range
if not (min_s <= speed <= max_s):
continue
# Otherwise filter by disc type
elif disc_type:
speed_ranges = {"Putter": (1, 3), "Midrange": (4, 6), "Fairway driver": (7, 9), "Distance driver": (10, 14)}
min_s, max_s = speed_ranges.get(disc_type, (1, 14))
if not (min_s <= speed <= max_s):
continue
sample_discs.append(f" • {name} ({data.get('manufacturer', '?')}): {speed}/{data.get('glide', 4)}/{data.get('turn', 0)}/{data.get('fade', 2)}")
added_discs.add(name)
if len(sample_discs) >= 35:
break
disc_context = "\n".join(sample_discs) if sample_discs else "Ingen relevante discs fundet"
# Build speed requirement text for AI
speed_requirement = ""
if custom_speed_range:
speed_requirement = f"""
🚫🚫🚫 SPEED-KRAV 🚫🚫🚫
Brugeren bad SPECIFIKT om speed {custom_speed_range[0]}-{custom_speed_range[1]}.
Du MÅ ABSOLUT KUN anbefale discs med speed {custom_speed_range[0]}, {(custom_speed_range[0]+custom_speed_range[1])//2}, eller {custom_speed_range[1]}.
Anbefal IKKE Leopard (speed 6), Buzzz (speed 5), eller andre discs UDENFOR dette interval!
Listen ovenfor indeholder KUN godkendte discs med korrekt speed."""
elif disc_type:
speed_ranges_text = {"Putter": "1-3", "Midrange": "4-6", "Fairway driver": "7-9", "Distance driver": "10-14"}
speed_requirement = f"\n⚠️ VIGTIGT: Brugeren bad om {disc_type}s (speed {speed_ranges_text.get(disc_type, '1-14')}). Anbefal KUN discs i dette interval!"
# Build AI prompt
ai_prompt = f"""Du er en venlig disc golf ekspert der hjælper brugere med at finde de rigtige discs.
Brugerens spørgsmål: "{prompt}"
{speed_requirement}
Brugerens niveau: {"Nybegynder" if skill_level == "beginner" else "Øvet" if skill_level == "intermediate" else "Erfaren"}
Estimeret kastelængde: ca. {max_dist}m
Søgeresultater fra nettet:
{search_results}
{kb_context}
Discs fra vores database (med PRÆCISE flight numbers) - VÆLG KUN FRA DENNE LISTE:
{disc_context}
REGLER:
1. Svar på dansk, venligt og hjælpsomt
2. ⚠️ ABSOLUT KRAV: Vælg KUN discs fra listen ovenfor. Listen er allerede filtreret til at matche brugerens krav!
3. ⭐ PRIORITER VELKENDTE DISCS: Discs øverst på listen er populære og anbefalet af Reddit-fællesskabet. Vælg helst disse fremfor ukendte discs længere nede på listen.
4. Hvis brugeren spørger om specifikke anbefalinger, giv 2-4 konkrete disc-forslag FRA LISTEN OVENFOR
5. ⚠️ KRITISK: Brug de NØJAGTIGE flight numbers fra databasen ovenfor. Opfind IKKE flight numbers!
6. Brug flight numbers format: Speed/Glide/Turn/Fade
7. Respekter brugerens speed-krav (fx hvis de siger "7-9 speed", må du KUN anbefale discs med speed 7, 8 eller 9)
8. For nybegyndere: anbefal understabile discs (turn -2 eller lavere) og lavere speed
9. Nævn vægt (begyndere: 150-165g, erfarne: 170-175g)
10. Brug Reddit-diskussioner når de er relevante - de viser hvad rigtige spillere faktisk bruger
11. Vær ærlig om hvad der passer til brugerens niveau
12. Hvis du beskriver discs som brugeren allerede har nævnt, brug PRÆCIS de flight numbers fra databasen
13. Hvis du ikke kan finde passende discs på listen, sig det ærligt i stedet for at anbefale forkerte discs
Hvis du anbefaler discs, brug dette format:
### **[DiscNavn]** af [Mærke]
- Flight: X/X/X/X (brug kun tal fra databasen ovenfor!)
- ✅ Hvorfor: ...
Afslut med at spørge om brugeren vil vide mere, sammenligne discs, eller se hvordan de flyver (flight chart)."""
try:
response = llm.invoke(ai_prompt).content
# POST-PROCESS: Fix any incorrect flight numbers in the response
response = fix_flight_numbers_in_response(response, DISC_DATABASE)
# POST-PROCESS: Fix any incorrect manufacturer names in the response
response = fix_manufacturer_names_in_response(response, DISC_DATABASE)
# POST-PROCESS: Remove disc recommendations outside the requested speed range
if custom_speed_range:
response = filter_wrong_speed_discs(response, DISC_DATABASE, custom_speed_range[0], custom_speed_range[1])
# Extract recommended disc names for potential flight chart
# First try bold text patterns, then fall back to searching full response
disc_names = []
response_lower = response.lower()
# Find all bold text patterns first
bold_matches = re.findall(r'\*\*([^*]+)\*\*', response)
for bold_text in bold_matches:
bold_lower = bold_text.lower().strip()
# Check if any disc name matches this bold text
for db_name in sorted(DISC_DATABASE.keys(), key=len, reverse=True):
if db_name.lower() == bold_lower or db_name.lower() in bold_lower:
if db_name not in disc_names:
disc_names.append(db_name)
break
if len(disc_names) >= 4:
break
# If we didn't find enough, also search for disc names mentioned without bold
# But only if they appear at start of line (like "Innova P2" or "P2")
if len(disc_names) < 4:
for db_name in sorted(DISC_DATABASE.keys(), key=len, reverse=True):
if db_name in disc_names:
continue
# Check for disc name at start of line or after manufacturer name
pattern = r'(?:^|\n)(?:[A-Za-z]+\s+)?(' + re.escape(db_name) + r')\b'
if re.search(pattern, response, re.IGNORECASE):
disc_names.append(db_name)
if len(disc_names) >= 4:
break
return {
'response': response,
'disc_names': disc_names[:4],
'skill_level': skill_level,
'max_dist': max_dist,
'disc_type': disc_type
}
except Exception as e:
return {
'response': f"Beklager, der opstod en fejl: {e}",
'disc_names': [],
'skill_level': skill_level,
'max_dist': max_dist,
'disc_type': disc_type
}
def render_flight_chart_comparison(disc_names, arm_speed='normal', throw_hand='right', throw_type='backhand'):
"""
Render a flight chart comparison using actual flight paths from database.
arm_speed: 'slow' (Begynder), 'normal' (Øvet), 'fast' (Pro)
throw_hand: 'right' or 'left'
throw_type: 'backhand' or 'forehand'
"""
import pandas as pd
# Determine if we need to mirror the chart
# Mirror for: left-handed backhand OR right-handed forehand
mirror_chart = (throw_hand == 'left' and throw_type == 'backhand') or \
(throw_hand == 'right' and throw_type == 'forehand')
# Map arm speed to Danish labels and path keys
arm_speed_info = {
'slow': {'label': 'Begynder', 'path_key': 'flight_path_bh_slow'},
'normal': {'label': 'Øvet', 'path_key': 'flight_path_bh_normal'},
'fast': {'label': 'Pro', 'path_key': 'flight_path_bh_fast'}
}
info = arm_speed_info.get(arm_speed, arm_speed_info['normal'])
path_key = info['path_key']
# Build throw description
hand_label = 'Venstrehåndet' if throw_hand == 'left' else 'Højrehåndet'
throw_label = 'Forhånd' if throw_type == 'forehand' else 'Baghånd'
st.markdown(f"### 🥏 Flight Chart Sammenligning")
st.markdown(f"*{hand_label} {throw_label} | Niveau: **{info['label']}***")
# Collect disc data from FULL database with flight paths
discs_with_data = []
not_found = []
for disc_name in disc_names:
disc_data = None
matched_name = None
for db_name, db_data in DISC_DATABASE_FULL.items():
if db_name.lower() == disc_name.lower():
disc_data = db_data
matched_name = db_name
break
if disc_data and disc_data.get(path_key):
discs_with_data.append({
'name': matched_name,
'speed': disc_data.get('speed', 5),
'glide': disc_data.get('glide', 4),
'turn': disc_data.get('turn', 0),
'fade': disc_data.get('fade', 2),
'manufacturer': disc_data.get('manufacturer', 'Ukendt'),
'path': disc_data.get(path_key, [])
})
else:
not_found.append(disc_name)
if not_found:
st.warning(f"Kunne ikke finde: {', '.join(not_found)}")
if not discs_with_data:
st.error("Ingen discs fundet med flight data.")
return
# Build chart data directly from database paths
all_data = []
for disc in discs_with_data:
path = disc['path']
if not path:
continue
# Add path points to chart data with point index for ordering
# Default: Negate x so turn goes LEFT, fade goes RIGHT (RHBH view)
# If mirrored: Don't negate (for LHBH or RHFH)
disc_label = f"{disc['name']} ({disc['speed']}/{disc['glide']}/{disc['turn']}/{disc['fade']})"
for i, p in enumerate(path):
x_value = p['x'] if mirror_chart else -p['x']
all_data.append({
'Disc': disc_label,
'Turn/Fade': x_value,
'Distance': round(p['y'] * 0.3048, 1), # Convert feet to meters
'point_order': i # Order for line connection
})
# Create chart using Altair
df = pd.DataFrame(all_data)
try:
import altair as alt
# Calculate axis ranges
max_dist = df['Distance'].max()
max_turn_fade = max(abs(df['Turn/Fade'].min()), abs(df['Turn/Fade'].max()), 2)
# Adjust axis title based on mirror state
if mirror_chart:
x_title = '← Turn | Fade →'
else:
x_title = '← Fade | Turn →'
chart = alt.Chart(df).mark_line(strokeWidth=3).encode(
x=alt.X('Turn/Fade:Q',
title=x_title,
axis=alt.Axis(labels=False, ticks=False),
scale=alt.Scale(domain=[-max_turn_fade - 0.5, max_turn_fade + 0.5])),
y=alt.Y('Distance:Q',
title='Distance (m)',
scale=alt.Scale(domain=[0, max_dist + 5])),
color=alt.Color('Disc:N', legend=alt.Legend(
orient='right',
title=None,
labelLimit=200 # Allow longer labels
)),
order='point_order:Q', # Connect points in sequence
tooltip=['Disc']
).properties(
width=750,
height=450
).configure_axis(
grid=True
).configure_legend(
labelFontSize=12
)
# Display full-width chart
st.altair_chart(chart, use_container_width=True)
# Show stock status for each disc
st.markdown("#### 🛒 Køb hos Disc Tree")
for disc in discs_with_data:
disc_name = disc['name']
stock_info = check_disc_tree_stock(disc_name)
if stock_info['status'] == 'in_stock':
price = stock_info.get('price', '')
price_text = f" ({price} kr)" if price else ""
st.markdown(f"✅ **{disc_name}**: [På lager{price_text}]({stock_info['url']})")
elif stock_info['status'] == 'sold_out':
st.markdown(f"⚠️ **{disc_name}**: [Udsolgt]({stock_info['url']})")
elif stock_info['status'] == 'not_found':
search_url = f"https://disctree.dk/search?q={disc_name.replace(' ', '+')}"
st.markdown(f"❌ **{disc_name}**: [Sælges ikke]({search_url})")
else:
# Unknown/error - just show search link
st.markdown(f"🔍 **{disc_name}**: [Søg]({stock_info.get('url', '')})")
except ImportError:
pivot_df = df.pivot(index='Distance', columns='Disc', values='Turn/Fade')
st.line_chart(pivot_df, height=450)
return True
# --- LOAD DISC DATABASE ---
# Flight data from https://flightcharts.dgputtheads.com/
@st.cache_data
def load_disc_database():
try:
with open("disc_database.json", "r") as f:
return json.load(f)
except:
return {}
@st.cache_data
def load_disc_database_full():
"""Load full database with flight paths."""
try:
with open("disc_database_full.json", "r") as f:
return json.load(f)
except:
return {}
DISC_DATABASE = load_disc_database()
DISC_DATABASE_FULL = load_disc_database_full()
def render_flight_chart(disc_name, speed, glide, turn, fade, arm_speed='normal', user_distance_m=None):
"""Render a flight chart using Streamlit's native chart."""
import pandas as pd
# Use continuous calculation if distance is provided
if user_distance_m is not None:
path = generate_flight_path(speed, glide, turn, fade, user_distance_m=user_distance_m)
stats = get_flight_stats(speed, glide, turn, fade, user_distance_m=user_distance_m)
factors = calculate_arm_speed_factor(user_distance_m, speed, glide)
else:
path = generate_flight_path(speed, glide, turn, fade, arm_speed)
stats = get_flight_stats(speed, glide, turn, fade, arm_speed)
factors = None
# Convert feet to meters for y-axis
df = pd.DataFrame([
{'Fade/Turn': p['x'], 'Distance (m)': round(p['y'] * 0.3048, 1)}
for p in path
])
# Create the chart
st.markdown(f"**{disc_name}** ({speed}/{glide}/{turn}/{fade})")
# Use columns for layout
col1, col2 = st.columns([2, 1])
with col1:
# Plot using st.line_chart with x and y swapped for vertical flight path
st.line_chart(
df,
x='Fade/Turn',
y='Distance (m)',
height=300
)
with col2:
if factors:
arm_pct = int(factors['arm_factor'] * 100)
if arm_pct >= 100:
st.metric("Din power", f"🚀 {arm_pct}%")
elif arm_pct >= 75:
st.metric("Din power", f"✅ {arm_pct}%")
else:
st.metric("Din power", f"⚠️ {arm_pct}%")
st.caption(f"Optimal: {factors['expected_dist_m']:.0f}m")
st.metric("Max distance", f"{stats['max_distance_m']}m")
st.metric("Max turn", f"{stats['max_turn']:.2f}")
st.metric("Fade", f"{stats['fade_amount']:.2f}")
def render_comparison_chart(discs_data, arm_speed='normal'):
"""Render comparison chart for multiple discs."""
import pandas as pd
all_data = []
for disc in discs_data:
name = disc['name']
path = generate_flight_path(
disc['speed'], disc['glide'], disc['turn'], disc['fade'],
arm_speed
)
for p in path:
all_data.append({
'Disc': name,
'Fade/Turn': p['x'],
'Distance (m)': round(p['y'] * 0.3048, 1)
})
df = pd.DataFrame(all_data)
# Pivot for multi-line chart
pivot_df = df.pivot(index='Distance (m)', columns='Disc', values='Fade/Turn')
st.line_chart(pivot_df, height=400)
def render_recommendation_flight_charts(disc_names, throwing_distance, database):
"""Render flight charts for recommended discs based on user's throwing distance."""
import pandas as pd
st.markdown(f"### 📈 Flight Charts (din kastelængde: {throwing_distance}m)")
# Collect disc data
discs_with_data = []
for disc_name in disc_names:
# Try to find the disc in database (case-insensitive)
disc_data = None
for db_name, db_data in database.items():
if db_name.lower() == disc_name.lower():
disc_data = db_data
disc_name = db_name # Use correct casing
break
if disc_data and disc_data.get('speed'):
discs_with_data.append({
'name': disc_name,
'speed': disc_data.get('speed', 5),
'glide': disc_data.get('glide', 4),
'turn': disc_data.get('turn', 0),
'fade': disc_data.get('fade', 2),
'manufacturer': disc_data.get('manufacturer', 'Ukendt')
})
if not discs_with_data:
return
# Generate paths for all discs using precise calculation
all_data = []
stats_data = []
for disc in discs_with_data:
# Use user_distance_m for precise calculation
path = generate_flight_path(
disc['speed'], disc['glide'], disc['turn'], disc['fade'],
user_distance_m=throwing_distance
)
stats = get_flight_stats(
disc['speed'], disc['glide'], disc['turn'], disc['fade'],
user_distance_m=throwing_distance
)
# Calculate arm speed factor for this specific disc
factors = calculate_arm_speed_factor(throwing_distance, disc['speed'], disc['glide'])
stats_data.append({
'name': disc['name'],
'distance': stats['max_distance_m'],
'turn': stats['max_turn'],
'fade': stats['fade_amount'],
'arm_factor': factors['arm_factor'],
'expected_dist': factors['expected_dist_m']
})
for p in path:
all_data.append({
'Disc': f"{disc['name']} ({disc['speed']}/{disc['glide']}/{disc['turn']}/{disc['fade']})",
'Turn/Fade': p['x'],
'Distance (m)': round(p['y'] * 0.3048, 1)
})
df = pd.DataFrame(all_data)
# Create pivot table for comparison chart
pivot_df = df.pivot(index='Distance (m)', columns='Disc', values='Turn/Fade')
# Show the chart
st.line_chart(pivot_df, height=350)
# Show stats table
st.markdown("**Sammenligning:**")
cols = st.columns(len(stats_data))
for i, stat in enumerate(stats_data):
with cols[i]:
st.markdown(f"**{stat['name']}**")
# Show arm factor as percentage
arm_pct = int(stat['arm_factor'] * 100)
if arm_pct >= 100:
arm_emoji = "🚀"
arm_text = f"{arm_pct}% power"
elif arm_pct >= 75:
arm_emoji = "✅"
arm_text = f"{arm_pct}% power"
else:
arm_emoji = "⚠️"
arm_text = f"Kun {arm_pct}%"
st.caption(f"{arm_emoji} {arm_text}")
st.caption(f"📏 Forventet: {stat['expected_dist']:.0f}m")
st.caption(f"↪️ Turn: {stat['turn']:.2f}")
st.caption(f"↩️ Fade: {stat['fade']:.2f}")
def get_disc_recommendations_by_distance(max_dist, disc_type, flight_pref, brand=None):
"""Get disc recommendations based on throwing distance and preferences."""
recommendations = []
# Map disc type to speed range
speed_ranges = {
"Putter": (1, 3),
"Midrange": (4, 6),
"Fairway driver": (7, 9),
"Distance driver": (10, 14)
}
min_speed, max_speed = speed_ranges.get(disc_type, (1, 14))
# Adjust max speed based on throwing distance
# Rule of thumb: You need ~10m per speed rating to throw a disc properly
recommended_max_speed = max_dist // 10
actual_max_speed = min(max_speed, recommended_max_speed)
for name, data in DISC_DATABASE.items():
speed = data.get("speed", 0)