File size: 46,733 Bytes
b58dcb8
 
 
 
 
bf79a43
 
 
 
 
 
 
 
b58dcb8
 
 
 
 
bf79a43
 
 
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06b88ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
 
 
bf79a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
b58dcb8
 
 
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
 
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
 
 
06b88ae
b957ce4
b58dcb8
 
 
 
b957ce4
b58dcb8
 
 
 
b957ce4
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
06b88ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06b88ae
 
 
 
 
 
b957ce4
 
 
 
 
 
 
06b88ae
 
 
 
 
 
 
 
 
 
 
b957ce4
 
06b88ae
b957ce4
 
b58dcb8
b957ce4
b58dcb8
bf79a43
b58dcb8
 
 
 
 
 
bf79a43
b58dcb8
 
 
 
 
 
bf79a43
 
 
 
 
 
 
b957ce4
bf79a43
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
b957ce4
 
 
 
 
 
 
 
 
bf79a43
 
b957ce4
bf79a43
 
 
 
b957ce4
 
 
bf79a43
b957ce4
 
 
bf79a43
b957ce4
 
 
 
 
 
 
 
 
 
bf79a43
 
b957ce4
bf79a43
 
 
 
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf79a43
 
b957ce4
bf79a43
 
 
 
 
 
 
 
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
bf79a43
 
 
 
 
 
 
b957ce4
bf79a43
b957ce4
bf79a43
 
 
b957ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
bf79a43
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e145117
b58dcb8
e145117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34804b5
e145117
 
 
34804b5
 
 
 
 
e145117
 
 
 
 
 
 
 
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
 
b58dcb8
 
 
 
 
b957ce4
b58dcb8
 
 
 
 
b957ce4
b58dcb8
 
b957ce4
 
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
 
b58dcb8
 
 
 
 
bf79a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
bf79a43
 
 
 
 
 
 
 
 
 
b957ce4
bf79a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b957ce4
bf79a43
 
 
 
 
 
 
2fbeaeb
 
 
 
 
 
0be956f
5ab45da
 
 
 
 
2fbeaeb
 
 
 
 
 
 
 
5ab45da
 
 
 
 
 
 
 
 
 
 
 
2fbeaeb
 
 
 
 
 
0be956f
5ab45da
2fbeaeb
 
5ab45da
2fbeaeb
5ab45da
2fbeaeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34804b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b417ecc
 
 
 
34804b5
 
b417ecc
 
 
 
34804b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b417ecc
34804b5
 
 
 
 
 
 
 
b417ecc
 
34804b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b417ecc
34804b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e7ed
34804b5
422e7ed
34804b5
422e7ed
 
 
 
 
 
34804b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b417ecc
34804b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
 
 
2fbeaeb
b58dcb8
2fbeaeb
b58dcb8
2fbeaeb
b58dcb8
 
 
 
8680350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
8680350
b58dcb8
 
 
 
 
 
 
 
 
 
 
 
2fbeaeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e145117
b58dcb8
e145117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b58dcb8
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
import gradio as gr
import os
from datetime import datetime
import json

# Import local modules
try:
    from voice_agent import AstrologyVoiceAgent
    VOICE_AVAILABLE = True
except ImportError:
    VOICE_AVAILABLE = False
    print("Voice agent not available - install elevenlabs package")

# Initialize with sponsor APIs (will be configured with environment variables)
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY", "")

# Initialize voice agent if available
voice_agent = AstrologyVoiceAgent(agent_type="teaching") if VOICE_AVAILABLE and ELEVENLABS_API_KEY else None

# Essential Dignities Tables
DOMICILE_RULERS = {
    "Aries": "Mars", "Taurus": "Venus", "Gemini": "Mercury",
    "Cancer": "Moon", "Leo": "Sun", "Virgo": "Mercury",
    "Libra": "Venus", "Scorpio": "Mars", "Sagittarius": "Jupiter",
    "Capricorn": "Saturn", "Aquarius": "Saturn", "Pisces": "Jupiter"
}

EXALTATIONS = {
    "Aries": "Sun", "Taurus": "Moon", "Gemini": None,
    "Cancer": "Jupiter", "Leo": None, "Virgo": "Mercury",
    "Libra": "Saturn", "Scorpio": None, "Sagittarius": None,
    "Capricorn": "Mars", "Aquarius": None, "Pisces": "Venus"
}

# Detriments (opposite sign of domicile rulership)
DETRIMENTS = {
    "Sun": ["Aquarius"],
    "Moon": ["Capricorn"],
    "Mercury": ["Sagittarius", "Pisces"],
    "Venus": ["Aries", "Scorpio"],
    "Mars": ["Taurus", "Libra"],
    "Jupiter": ["Gemini", "Virgo"],
    "Saturn": ["Cancer", "Leo"]
}

# Falls (opposite sign of exaltation)
FALLS = {
    "Sun": ["Libra"],
    "Moon": ["Scorpio"],
    "Mercury": ["Pisces"],
    "Venus": ["Virgo"],
    "Mars": ["Cancer"],
    "Jupiter": ["Capricorn"],
    "Saturn": ["Aries"]
}

TRIPLICITIES = {
    "Fire": {"day": "Sun", "night": "Jupiter", "participating": "Saturn"},
    "Earth": {"day": "Venus", "night": "Moon", "participating": "Mars"},
    "Air": {"day": "Saturn", "night": "Mercury", "participating": "Jupiter"},
    "Water": {"day": "Venus", "night": "Mars", "participating": "Moon"}
}

SIGN_TRIPLICITIES = {
    "Aries": "Fire", "Leo": "Fire", "Sagittarius": "Fire",
    "Taurus": "Earth", "Virgo": "Earth", "Capricorn": "Earth",
    "Gemini": "Air", "Libra": "Air", "Aquarius": "Air",
    "Cancer": "Water", "Scorpio": "Water", "Pisces": "Water"
}

# Egyptian Bounds (Terms)
EGYPTIAN_BOUNDS = {
    "Aries": [(0, 6, "Jupiter"), (6, 12, "Venus"), (12, 20, "Mercury"), (20, 25, "Mars"), (25, 30, "Saturn")],
    "Taurus": [(0, 8, "Venus"), (8, 14, "Mercury"), (14, 22, "Jupiter"), (22, 27, "Saturn"), (27, 30, "Mars")],
    "Gemini": [(0, 6, "Mercury"), (6, 12, "Jupiter"), (12, 17, "Venus"), (17, 24, "Mars"), (24, 30, "Saturn")],
    "Cancer": [(0, 7, "Mars"), (7, 13, "Venus"), (13, 19, "Mercury"), (19, 26, "Jupiter"), (26, 30, "Saturn")],
    "Leo": [(0, 6, "Jupiter"), (6, 11, "Venus"), (11, 18, "Saturn"), (18, 24, "Mercury"), (24, 30, "Mars")],
    "Virgo": [(0, 7, "Mercury"), (7, 17, "Venus"), (17, 21, "Jupiter"), (21, 28, "Mars"), (28, 30, "Saturn")],
    "Libra": [(0, 6, "Saturn"), (6, 14, "Mercury"), (14, 21, "Jupiter"), (21, 28, "Venus"), (28, 30, "Mars")],
    "Scorpio": [(0, 7, "Mars"), (7, 11, "Venus"), (11, 19, "Mercury"), (19, 24, "Jupiter"), (24, 30, "Saturn")],
    "Sagittarius": [(0, 12, "Jupiter"), (12, 17, "Venus"), (17, 21, "Mercury"), (21, 26, "Saturn"), (26, 30, "Mars")],
    "Capricorn": [(0, 7, "Mercury"), (7, 14, "Jupiter"), (14, 22, "Venus"), (22, 26, "Saturn"), (26, 30, "Mars")],
    "Aquarius": [(0, 7, "Mercury"), (7, 13, "Venus"), (13, 20, "Jupiter"), (20, 25, "Mars"), (25, 30, "Saturn")],
    "Pisces": [(0, 12, "Venus"), (12, 16, "Jupiter"), (16, 19, "Mercury"), (19, 28, "Mars"), (28, 30, "Saturn")]
}

# Decans (Faces)
DECANS = {
    "Aries": [(0, 10, "Mars"), (10, 20, "Sun"), (20, 30, "Venus")],
    "Taurus": [(0, 10, "Mercury"), (10, 20, "Moon"), (20, 30, "Saturn")],
    "Gemini": [(0, 10, "Jupiter"), (10, 20, "Mars"), (20, 30, "Sun")],
    "Cancer": [(0, 10, "Venus"), (10, 20, "Mercury"), (20, 30, "Moon")],
    "Leo": [(0, 10, "Saturn"), (10, 20, "Jupiter"), (20, 30, "Mars")],
    "Virgo": [(0, 10, "Sun"), (10, 20, "Venus"), (20, 30, "Mercury")],
    "Libra": [(0, 10, "Moon"), (10, 20, "Saturn"), (20, 30, "Jupiter")],
    "Scorpio": [(0, 10, "Mars"), (10, 20, "Sun"), (20, 30, "Venus")],
    "Sagittarius": [(0, 10, "Mercury"), (10, 20, "Moon"), (20, 30, "Saturn")],
    "Capricorn": [(0, 10, "Jupiter"), (10, 20, "Mars"), (20, 30, "Sun")],
    "Aquarius": [(0, 10, "Venus"), (10, 20, "Mercury"), (20, 30, "Moon")],
    "Pisces": [(0, 10, "Saturn"), (10, 20, "Jupiter"), (20, 30, "Mars")]
}

# Zodiacal Releasing
ZODIACAL_RELEASING_ORDER = [
    "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius",
    "Capricorn", "Aquarius", "Pisces", "Aries", "Taurus", "Gemini"
]

SIGN_YEARS = {
    "Cancer": 25, "Leo": 19, "Virgo": 20, "Libra": 8, "Scorpio": 15,
    "Sagittarius": 12, "Capricorn": 27, "Aquarius": 30, "Pisces": 12,
    "Aries": 15, "Taurus": 8, "Gemini": 20
}

def calculate_profections(birth_year: int, target_year: int) -> str:
    """Calculate annual profections from Ascendant"""
    age = target_year - birth_year
    profected_house = (age % 12) + 1

    house_meanings = {
        1: "Self, body, vitality, life direction",
        2: "Resources, money, possessions, values",
        3: "Siblings, communication, short journeys, learning",
        4: "Home, family, parents, foundations, endings",
        5: "Children, creativity, pleasure, speculation",
        6: "Health, work, service, daily routines, pets",
        7: "Partnership, marriage, open enemies, contracts",
        8: "Death, transformation, shared resources, inheritance",
        9: "Higher learning, travel, philosophy, religion",
        10: "Career, reputation, authority, public life",
        11: "Friends, groups, hopes, wishes, benefactors",
        12: "Hidden matters, spirituality, isolation, undoing"
    }

    return f"""## Annual Profections

**Birth Year:** {birth_year}
**Target Year:** {target_year}
**Age:** {age}

### Profected House: {profected_house}th House

**Significations:** {house_meanings[profected_house]}

### Lord of the Year:
The ruler of your natal {profected_house}th house becomes your "Lord of the Year" for age {age}.

**How to use this:**
1. Identify which sign is on the cusp of your natal {profected_house}th house
2. The ruler of that sign is activated for this entire year
3. Pay attention to:
   - Transits to the Lord of the Year
   - The condition of the Lord in your natal chart
   - Any planets in your natal {profected_house}th house (also activated)

**Technique from:** Vettius Valens (*Anthology*, Book 4) and Paulus Alexandrinus

### How Profections Work:
Each year of life corresponds to one house, counted from the Ascendant:
- Age 0-11 months: 1st house
- Age 1: 2nd house
- Age 12: Returns to 1st house (first profection return)
- Age {age}: {profected_house}th house

Every 12 years, you return to the same house, creating profection return years.
"""

def assess_planetary_dignity(planet: str, sign: str, is_day_chart: bool) -> str:
    """Assess a planet's essential dignity in a given sign"""
    dignity_score = 0
    dignities = []
    debilities = []

    # Check domicile (+5)
    if DOMICILE_RULERS.get(sign) == planet:
        dignity_score += 5
        dignities.append("Domicile (+5)")

    # Check exaltation (+4)
    if EXALTATIONS.get(sign) == planet:
        dignity_score += 4
        dignities.append("Exaltation (+4)")

    # Check triplicity (+3)
    triplicity = SIGN_TRIPLICITIES.get(sign)
    if triplicity:
        triplicity_rulers = TRIPLICITIES[triplicity]
        if is_day_chart and triplicity_rulers["day"] == planet:
            dignity_score += 3
            dignities.append("Triplicity Ruler - Day (+3)")
        elif not is_day_chart and triplicity_rulers["night"] == planet:
            dignity_score += 3
            dignities.append("Triplicity Ruler - Night (+3)")
        elif triplicity_rulers["participating"] == planet:
            dignity_score += 3
            dignities.append("Triplicity Ruler - Participating (+3)")

    # Check detriment (-5)
    if sign in DETRIMENTS.get(planet, []):
        dignity_score -= 5
        debilities.append("Detriment (-5)")

    # Check fall (-4)
    if sign in FALLS.get(planet, []):
        dignity_score -= 4
        debilities.append("Fall (-4)")

    # Determine condition based on score
    if dignity_score <= -4:
        condition = "Debilitated"
    elif dignity_score < 0:
        condition = "Weak"
    elif dignity_score == 0:
        condition = "Peregrine (no essential dignity)"
    elif dignity_score <= 3:
        condition = "Minor Dignity"
    else:
        condition = "Strong"

    chart_type = "Day Chart" if is_day_chart else "Night Chart"

    # Format as readable text
    result = f"""## Essential Dignity Analysis

**Planet:** {planet}
**Sign:** {sign}
**Chart Type:** {chart_type}

### Dignity Assessment:
"""
    if dignities:
        for dignity in dignities:
            result += f"βœ“ {dignity}\n"
    else:
        result += "β—‹ No major dignities\n"

    if debilities:
        result += "\n### Debilities:\n"
        for debility in debilities:
            result += f"βœ— {debility}\n"

    result += f"""
**Total Dignity Score:** {dignity_score} points
**Planetary Condition:** {condition}

### Interpretation:
"""
    if dignity_score <= -5:
        result += f"{planet} is severely debilitated in {sign}, being in detriment. The planet struggles to express its nature and may act contrary to its essential significations."
    elif dignity_score == -4:
        result += f"{planet} is in fall in {sign}, a position of weakness. The planet cannot act with full strength and may produce difficult outcomes."
    elif dignity_score < 0:
        result += f"{planet} is weakened in {sign} with mixed conditions. The debilities outweigh any minor dignities present."
    elif dignity_score == 0:
        result += f"{planet} is peregrine in {sign}, having no essential dignity. The planet is like a stranger in a foreign land, neither particularly strong nor weak, but without support."
    elif dignity_score <= 3:
        result += f"{planet} has minor dignity in {sign}. The planet has some support but is not at full strength."
    elif dignity_score >= 5:
        result += f"{planet} is very well-placed in {sign}, having its domicile or maximum dignity. The planet can act with full strength and autonomy."
    else:
        result += f"{planet} is strong in {sign}, with significant essential dignity. The planet functions well and can express its significations effectively."

    return result

def calculate_lots(asc_degree: float, sun_degree: float, moon_degree: float, is_day_chart: bool) -> str:
    """Calculate traditional Hellenistic lots (Fortuna and Spirit)"""

    if is_day_chart:
        # Lot of Fortune (day): Asc + Moon - Sun
        fortune = (asc_degree + moon_degree - sun_degree) % 360
    else:
        # Lot of Fortune (night): Asc + Sun - Moon
        fortune = (asc_degree + sun_degree - moon_degree) % 360

    if is_day_chart:
        # Lot of Spirit (day): Asc + Sun - Moon
        spirit = (asc_degree + sun_degree - moon_degree) % 360
    else:
        # Lot of Spirit (night): Asc + Moon - Sun
        spirit = (asc_degree + moon_degree - sun_degree) % 360

    # Convert to sign and degree
    def deg_to_sign(deg):
        signs = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
                 "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]
        sign_num = int(deg // 30)
        sign_deg = deg % 30
        return signs[sign_num], round(sign_deg, 2)

    chart_type = "Day Chart" if is_day_chart else "Night Chart"
    fortune_sign, fortune_deg = deg_to_sign(fortune)
    spirit_sign, spirit_deg = deg_to_sign(spirit)

    formula_fortune = "Asc + Moon - Sun" if is_day_chart else "Asc + Sun - Moon"
    formula_spirit = "Asc + Sun - Moon" if is_day_chart else "Asc + Moon - Sun"

    result = f"""## Traditional Hellenistic Lots

**Chart Type:** {chart_type}

### Lot of Fortune (Fortuna)
**Position:** {fortune_deg}Β° {fortune_sign} ({round(fortune, 2)}Β° absolute)
**Formula ({chart_type}):** {formula_fortune}
**Signifies:** Material fortune, body, health, general life circumstances

### Lot of Spirit
**Position:** {spirit_deg}Β° {spirit_sign} ({round(spirit, 2)}Β° absolute)
**Formula ({chart_type}):** {formula_spirit}
**Signifies:** Spirit, reputation, career, action in the world

### Notes:
- Lot formulas reverse for day vs night charts (sect consideration)
- In {chart_type.lower()}, Fortune = {formula_fortune}
- Fortune is used for Zodiacal Releasing of general life topics
- Spirit is used for Zodiacal Releasing of career and reputation
"""
    return result

def get_bound_ruler(sign: str, degree: float) -> str:
    """Get the Egyptian bound (term) ruler for a planet's position"""
    if sign not in EGYPTIAN_BOUNDS:
        return f"❌ Error: Invalid sign '{sign}'"

    bounds = EGYPTIAN_BOUNDS[sign]
    for start, end, ruler in bounds:
        if start <= degree < end:
            return f"""## Egyptian Bounds (Terms)

**Position:** {degree}Β° {sign}

### Bound Ruler: {ruler}
**Range:** {start}Β°-{end}Β° of {sign}
**Dignity Points:** +2

### All Bounds in {sign}:
"""+ "\n".join([f"- {s}Β°-{e}Β°: {r}" for s, e, r in bounds]) + f"""

### Significance:
The Egyptian bounds divide each sign into 5 unequal sections, each ruled by a different planet. A planet in its own bound gains +2 dignity points. Bounds are used in time-lord techniques and provide refined dignity assessment.
"""

    return f"❌ Error: Degree {degree} is out of range (must be 0-30)"

def get_decan_ruler(sign: str, degree: float) -> str:
    """Get the decan (face) ruler for a planet's position"""
    if sign not in DECANS:
        return f"❌ Error: Invalid sign '{sign}'"

    decans = DECANS[sign]
    for start, end, ruler in decans:
        if start <= degree < end:
            decan_num = (start // 10) + 1
            return f"""## Decans (Faces)

**Position:** {degree}Β° {sign}

### Decan Ruler: {ruler}
**Decan:** {decan_num} of 3 ({start}Β°-{end}Β°)
**Dignity Points:** +1

### All Decans in {sign}:
- 1st Decan (0Β°-10Β°): {decans[0][2]}
- 2nd Decan (10Β°-20Β°): {decans[1][2]}
- 3rd Decan (20Β°-30Β°): {decans[2][2]}

### Significance:
Decans (also called "faces") divide each sign into three equal 10Β° sections. Each decan is ruled by a planet following the Chaldean order. A planet in its own decan gains +1 dignity point.
"""

    return f"❌ Error: Degree {degree} is out of range (must be 0-30)"

def calculate_zodiacal_releasing(starting_sign: str, birth_year: int, target_year: int = None) -> str:
    """Calculate Zodiacal Releasing periods (simplified version)"""
    if starting_sign not in ZODIACAL_RELEASING_ORDER:
        return f"❌ Error: Invalid starting sign '{starting_sign}'"

    if target_year is None:
        target_year = datetime.now().year

    age = target_year - birth_year
    current_index = ZODIACAL_RELEASING_ORDER.index(starting_sign)
    accumulated_years = 0

    result = f"""## Zodiacal Releasing (Loosing of the Bond)

**Starting Sign:** {starting_sign} (from Lot of Fortune or Spirit)
**Birth Year:** {birth_year}
**Current Year:** {target_year}
**Current Age:** {age}

### Major Periods:

"""

    # Calculate first 8 periods for display
    for i in range(8):
        sign = ZODIACAL_RELEASING_ORDER[(current_index + i) % 12]
        period_years = SIGN_YEARS[sign]

        start_age = int(accumulated_years)
        end_age = int(accumulated_years + period_years)

        is_current = start_age <= age < end_age
        marker = " ← **CURRENT PERIOD**" if is_current else ""

        result += f"{i+1}. **{sign}** - Ages {start_age}-{end_age} ({period_years} years){marker}\n"

        accumulated_years += period_years

    result += f"""
### About Zodiacal Releasing:

From Vettius Valens' *Anthology*, this sophisticated timing technique uses a fixed planetary order through the zodiac signs. Each sign grants a specific number of years:

**Sign Years:**
- Cancer: 25 | Leo: 19 | Virgo: 20 | Libra: 8
- Scorpio: 15 | Sagittarius: 12 | Capricorn: 27 | Aquarius: 30
- Pisces: 12 | Aries: 15 | Taurus: 8 | Gemini: 20

This is a simplified view showing major periods. Full ZR includes minor and sub-minor divisions for precise timing.
"""

    return result

def research_hellenistic_topic(query: str) -> str:
    """Research assistant for Hellenistic astrology topics"""
    # This will integrate with OpenAI/Anthropic APIs
    # For now, return educational placeholder
    
    topics = {
        "sect": """Sect Theory (Hairesis)
        
According to Vettius Valens (Anthology, Book III), sect distinguishes between day and night charts:

**Day Chart (Diurnal)**: Sun above horizon at birth
- Benefics: Jupiter, Saturn (traditionally)
- Malefics: Mars more difficult than Saturn
- Solar sect planets: Sun, Jupiter, Saturn

**Night Chart (Nocturnal)**: Sun below horizon at birth  
- Benefics: Venus, Moon
- Malefics: Saturn more difficult than Mars
- Lunar sect planets: Moon, Venus, Mars

**Practical Application**:
Ptolemy (Tetrabiblos, Book III) emphasizes that planets in their proper sect are strengthened, while planets contrary to sect are weakened. A day chart with Jupiter angular is far more favorable than Saturn in the same position.

**Source Differences**:
- Valens: More emphasis on sect in time-lord systems
- Ptolemy: More theoretical, applies to natal interpretation
- Dorotheus: Less explicit about sect distinctions
""",
        "profections": """Annual Profections (Epembasis)

The technique advances one house per year of life from the Ascendant.

**Method** (from Valens, Anthology Book IV):
1. Count age in complete years
2. Each year = one house from Ascendant
3. The profected house's ruler becomes the "Lord of the Year"

**Example**:
- Age 0-11 months: 1st house
- Age 1: 2nd house  
- Age 12: Returns to 1st house (first return)
- Age 25: 2nd house (third time)

**Application**:
The Lord of the Year is activated. Transits to that planet are significant. The house profected to shows the area of life emphasis.

**Paulus Alexandrinus** adds that planets in the profected house are also activated that year.
""",
        "bounds": """Egyptian Bounds (Terms)

Each sign is divided into five unequal sections, each ruled by a planet.

**Ptolemy vs Egyptian System**:
Ptolemy (Tetrabiblos I.21) presents his own system, but most practitioners use the older Egyptian bounds found in Valens.

**Significance** (per Valens):
- Bounds = +2 dignity points
- Show more refined planet influence within a sign
- Used in time-lord distributions

**Example - Aries** (Egyptian):
- 0-6Β°: Jupiter
- 6-12Β°: Venus
- 12-20Β°: Mercury
- 20-25Β°: Mars
- 25-30Β°: Saturn
"""
    }
    
    # Simple keyword matching
    query_lower = query.lower()
    for keyword, content in topics.items():
        if keyword in query_lower:
            return content
    
    return f"""Research Query: "{query}"

This would integrate with OpenAI/Anthropic to search through:
- Vettius Valens (Anthology)
- Ptolemy (Tetrabiblos)  
- Dorotheus (Carmen Astrologicum)
- Modern synthesizers: Chris Brennan, Demetra George

Please implement API keys to enable full research capabilities.
"""

# Gradio Interface
def create_demo():
    with gr.Blocks(
        theme=gr.themes.Soft(primary_hue="purple", secondary_hue="blue"),
        title="HERMES - Hellenistic Astrology Research Assistant"
    ) as demo:
        
        gr.Markdown("""
        # πŸ›οΈ HERMES - Hellenistic Ephemeris Research & MCP Educational System

        **Ancient Wisdom Meets Modern AI**

        An interactive research and teaching tool for traditional Hellenistic astrology, combining 2000-year-old techniques
        from ancient Greek and Roman astrologers with modern AI agents and the Model Context Protocol (MCP).

        ## ✨ What You Can Do Here:

        ### πŸ“Š Chart Calculations
        - **Essential Dignities** - Assess planetary strength through domicile, exaltation, and triplicity
        - **Traditional Lots** - Calculate the Lots of Fortune and Spirit with proper sect consideration
        - **Egyptian Bounds** - Determine bound (term) rulers for refined dignity assessment
        - **Decans (Faces)** - Find decan rulers following the Chaldean order

        ### ⏱️ Time-Lord Techniques
        - **Annual Profections** - Discover your Lord of the Year for any age
        - **Zodiacal Releasing** - Explore major life periods from Vettius Valens' system

        ### πŸŽ“ Learn Traditional Astrology
        - **Text-Based Teaching** - AI-powered explanations of Hellenistic techniques
        - **Source Research** - Educational content citing ancient texts
        - **Study Resources** - Curated books, courses, and free learning materials

        ### 🌐 External Integrations
        - **Astroseek MCP** - Fetch chart data from external sources (proof-of-concept)
        - **Modal Serverless** - 6 MCP functions deployed for calculations
        - **Local Fallback** - All calculations available offline

        ### πŸ›οΈ Built on Ancient Foundations
        All techniques are drawn from authentic Hellenistic sources (1st-7th century CE),
        not modern psychological astrology. We preserve the traditional methods exactly as
        taught by Valens, Ptolemy, and Dorotheus.

        ---

        **Built for the MCP 1st Birthday Hackathon** | Powered by OpenAI, Anthropic, ElevenLabs & Modal
        """)
        
        with gr.Tab("πŸ“Š Chart Analysis"):
            gr.Markdown("### Essential Dignity Calculator")
            
            with gr.Row():
                planet_input = gr.Dropdown(
                    choices=["Sun", "Moon", "Mercury", "Venus", "Mars", "Jupiter", "Saturn"],
                    label="Planet",
                    value="Sun"
                )
                sign_input = gr.Dropdown(
                    choices=list(DOMICILE_RULERS.keys()),
                    label="Sign",
                    value="Aries"
                )
                sect_input = gr.Checkbox(label="Day Chart (uncheck for Night Chart)", value=True)
            
            dignity_btn = gr.Button("Assess Planetary Condition", variant="primary")
            dignity_output = gr.Markdown(label="Dignity Analysis")

            dignity_btn.click(
                fn=assess_planetary_dignity,
                inputs=[planet_input, sign_input, sect_input],
                outputs=dignity_output
            )

            gr.Markdown("### Lot Calculator")
            with gr.Row():
                asc_deg = gr.Number(label="Ascendant (degrees 0-360)", value=0)
                sun_deg = gr.Number(label="Sun (degrees 0-360)", value=45)
                moon_deg = gr.Number(label="Moon (degrees 0-360)", value=180)

            lot_sect = gr.Checkbox(label="Day Chart", value=True)
            lot_btn = gr.Button("Calculate Lots", variant="primary")
            lot_output = gr.Markdown(label="Traditional Lots")

            lot_btn.click(
                fn=calculate_lots,
                inputs=[asc_deg, sun_deg, moon_deg, lot_sect],
                outputs=lot_output
            )
        
        with gr.Tab("πŸ“š Source Research"):
            gr.Markdown("""
            ### Hellenistic Astrology Knowledge Base
            Ask about traditional techniques and get answers citing ancient sources.
            """)
            
            research_query = gr.Textbox(
                label="Research Question",
                placeholder="e.g., 'Explain sect theory' or 'What are profections?' or 'Describe Egyptian bounds'",
                lines=2
            )
            
            research_btn = gr.Button("Search Ancient Sources", variant="primary")
            research_output = gr.Textbox(label="Research Results", lines=20)
            
            research_btn.click(
                fn=research_hellenistic_topic,
                inputs=research_query,
                outputs=research_output
            )
            
            gr.Markdown("""
            **Sources Referenced:**
            - Vettius Valens (*Anthology*)
            - Ptolemy (*Tetrabiblos*)
            - Dorotheus of Sidon (*Carmen Astrologicum*)
            - Paulus Alexandrinus
            - Modern: Chris Brennan, Demetra George, Robert Schmidt
            """)
        
        with gr.Tab("⏱️ Time-Lord Systems"):
            gr.Markdown("### Annual Profections Calculator")
            
            with gr.Row():
                birth_year_input = gr.Number(label="Birth Year", value=1990)
                target_year_input = gr.Number(label="Target Year", value=2025)
            
            profection_btn = gr.Button("Calculate Profections", variant="primary")
            profection_output = gr.Markdown(label="Profection Results")

            profection_btn.click(
                fn=calculate_profections,
                inputs=[birth_year_input, target_year_input],
                outputs=profection_output
            )

        with gr.Tab("🎯 Bounds & Decans"):
            gr.Markdown("""
            ### Egyptian Bounds (Terms) & Decans (Faces)
            Calculate the sub-rulerships within each sign for refined essential dignity assessment.
            """)

            with gr.Row():
                bound_sign = gr.Dropdown(
                    choices=list(DOMICILE_RULERS.keys()),
                    label="Sign",
                    value="Aries"
                )
                bound_degree = gr.Number(label="Degree (0-30)", value=15, minimum=0, maximum=30)

            with gr.Row():
                bound_btn = gr.Button("Get Bound Ruler", variant="primary")
                decan_btn = gr.Button("Get Decan Ruler", variant="secondary")

            bound_output = gr.Markdown(label="Results")

            bound_btn.click(
                fn=get_bound_ruler,
                inputs=[bound_sign, bound_degree],
                outputs=bound_output
            )

            decan_btn.click(
                fn=get_decan_ruler,
                inputs=[bound_sign, bound_degree],
                outputs=bound_output
            )

            gr.Markdown("""
            **About Bounds & Decans:**

            - **Egyptian Bounds** (Terms): Each sign divided into 5 unequal sections ruled by planets (+2 dignity points)
            - **Decans** (Faces): Each sign divided into 3 equal 10Β° sections (+1 dignity point)

            These sub-rulers provide more refined assessment of planetary condition and are used in advanced time-lord techniques.

            Source: Vettius Valens, Ptolemy (though he presents his own bounds system)
            """)

        with gr.Tab("🌟 Zodiacal Releasing"):
            gr.Markdown("""
            ### Zodiacal Releasing (Loosing of the Bond)
            Advanced time-lord system from Vettius Valens using the Lot of Fortune or Spirit.
            """)

            with gr.Row():
                zr_starting_sign = gr.Dropdown(
                    choices=ZODIACAL_RELEASING_ORDER,
                    label="Starting Sign (where Lot of Fortune/Spirit falls)",
                    value="Cancer"
                )

            with gr.Row():
                zr_birth_year = gr.Number(label="Birth Year", value=1990)
                zr_target_year = gr.Number(label="Target Year (optional)", value=2025)

            zr_btn = gr.Button("Calculate Zodiacal Releasing Periods", variant="primary")
            zr_output = gr.Markdown(label="ZR Periods")

            zr_btn.click(
                fn=calculate_zodiacal_releasing,
                inputs=[zr_starting_sign, zr_birth_year, zr_target_year],
                outputs=zr_output
            )

        with gr.Tab("πŸŽ“ Learning Center"):
            gr.Markdown("""
            ### Interactive Voice Teaching
            Learn Hellenistic astrology techniques with AI-powered voice explanations.
            """)

            if voice_agent and ELEVENLABS_API_KEY:
                gr.Markdown("""
                ⚠️ **Voice Feature Status**: ElevenLabs audio requires a paid subscription when running on HuggingFace Spaces (free tier blocked due to proxy detection).

                Text explanations are fully available below! For voice audio, consider running HERMES locally.
                """)

                technique_choice = gr.Dropdown(
                    choices=["Annual Profections", "Sect Theory", "Zodiacal Releasing",
                             "Essential Dignities", "Lots (Fortune & Spirit)", "Bounds & Decans"],
                    label="Choose a Technique to Learn",
                    value="Annual Profections"
                )

                teach_btn = gr.Button("πŸ“– Get Text Explanation", variant="primary")

                text_output = gr.Textbox(
                    label="Text Explanation",
                    lines=20,
                    max_lines=30,
                    show_copy_button=True,
                    container=True
                )

                def get_teaching_explanation(technique):
                    """Get text explanation (audio disabled due to ElevenLabs free tier restrictions on HF Spaces)"""
                    technique_map = {
                        "Annual Profections": "annual_profections",
                        "Sect Theory": "sect_theory",
                        "Zodiacal Releasing": "zodiacal_releasing"
                    }
                    key = technique_map.get(technique, technique.lower().replace(" ", "_"))
                    text = voice_agent.explain_technique(key)
                    return text

                teach_btn.click(
                    fn=get_teaching_explanation,
                    inputs=technique_choice,
                    outputs=text_output
                )
            else:
                gr.Markdown("⚠️ Voice teaching requires ELEVENLABS_API_KEY to be set in environment")
                gr.Markdown("Add the API key in HuggingFace Space Settings β†’ Repository Secrets")

            gr.Markdown("""
            ---
            ### πŸ“š Educational Resources

            **Recommended Books:**
            - **Chris Brennan** - [*Hellenistic Astrology: The Study of Fate and Fortune*](https://www.hellenisticastrology.com/book/)
              - Comprehensive modern treatment of traditional techniques
              - Available at: https://www.hellenisticastrology.com
            - **Demetra George** - *Ancient Astrology in Theory and Practice* (2 volumes)
            - **Vettius Valens** - *The Anthology* (Project Hindsight translation)
            - **Claudius Ptolemy** - *Tetrabiblos* (Schmidt translation)

            **Online Resources:**
            - [The Astrology Podcast](https://theastrologypodcast.com) by Chris Brennan
            - [Hellenistic Astrology Website](https://www.hellenisticastrology.com) - Courses, articles, chart examples
            - [Project Hindsight](http://www.projecthindsight.com) - Ancient text translations

            **Free Learning:**
            - Chris Brennan's YouTube channel - Technique tutorials and demonstrations
            - [Astrology Podcast Episodes on Hellenistic Techniques](https://theastrologypodcast.com/hellenistic-astrology/)

            **Study Path:**
            1. Start with essential dignities and sect
            2. Learn the lot calculations (Fortune, Spirit)
            3. Master annual profections for yearly forecasting
            4. Progress to zodiacal releasing for life periods
            5. Explore bounds, decans, and advanced timing
            """)

        with gr.Tab("🌐 External Charts (Astroseek)"):
            gr.Markdown("""
            ### Astroseek.com Chart Integration

            Fetch chart data from external sources via MCP integration.

            ⚠️ **Note**: This is a proof-of-concept web scraping integration.
            For production use, consider official APIs or local ephemeris calculations.
            """)

            with gr.Row():
                with gr.Column():
                    gr.Markdown("#### Birth Data")

                    astro_date = gr.Textbox(
                        label="Birth Date (YYYY-MM-DD)",
                        placeholder="1990-01-15",
                        value="1990-01-15"
                    )

                    astro_time = gr.Textbox(
                        label="Birth Time (HH:MM)",
                        placeholder="12:00",
                        value="12:00"
                    )

                    astro_city = gr.Textbox(
                        label="City",
                        placeholder="New York",
                        value="New York"
                    )

                    astro_country = gr.Textbox(
                        label="Country (optional)",
                        placeholder="USA",
                        value="USA"
                    )

                    astro_chart_btn = gr.Button("πŸ” Fetch Chart from Astroseek", variant="primary")

                with gr.Column():
                    gr.Markdown("#### Daily Horoscope")

                    astro_sign = gr.Dropdown(
                        choices=["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
                                "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"],
                        label="Zodiac Sign",
                        value="Aries"
                    )

                    astro_horoscope_btn = gr.Button("πŸ“– Get Daily Horoscope", variant="secondary")

            astro_output = gr.Textbox(
                label="Results",
                lines=25,
                max_lines=40,
                show_copy_button=True
            )

            def fetch_astroseek_chart(date, time, city, country):
                """Fetch chart from Astroseek"""
                try:
                    from astroseek_mcp import AstroseekMCP

                    client = AstroseekMCP()
                    result = client.calculate_chart(
                        birth_date=date,
                        birth_time=time,
                        city=city,
                        country=country
                    )

                    if "error" in result:
                        return f"""## ❌ Error Fetching Chart

**Error Message**: {result['error']}

**Note**: {result.get('note', 'Web scraping integration may require updates.')}

### Troubleshooting:
- Check internet connection
- Verify Astroseek.com is accessible
- This is a proof-of-concept integration
- Consider using local ephemeris (pyswisseph) instead

### Alternative:
Use the main HERMES calculators in other tabs for:
- Essential Dignities
- Lots (Fortune, Spirit)
- Annual Profections
- Zodiacal Releasing
- Bounds & Decans
"""

                    # Format the result
                    output = f"""## πŸ“Š Chart Data from Astroseek.com

**Birth Date**: {result.get('birth_date', 'N/A')}
**Birth Time**: {result.get('birth_time', 'N/A')}
**Location**: {result.get('location', 'N/A')}

### Planet Positions:
"""
                    planets = result.get('planets', {})
                    if planets:
                        for planet, data in planets.items():
                            output += f"- **{planet}**: {data.get('position', 'N/A')}"
                            if data.get('retrograde'):
                                output += " β„ž (Retrograde)"
                            output += "\n"
                    else:
                        output += "*No planet data available (HTML parsing may need update)*\n"

                    output += "\n### House Cusps:\n"
                    houses = result.get('houses', [])
                    if houses:
                        for house in houses:
                            output += f"- **House {house.get('house', '?')}**: {house.get('cusp', 'N/A')}\n"
                    else:
                        output += "*No house data available*\n"

                    output += "\n### Aspects:\n"
                    aspects = result.get('aspects', [])
                    if aspects:
                        for aspect in aspects[:10]:  # Show first 10
                            output += f"- {aspect.get('planet1', '?')} {aspect.get('aspect', '?')} {aspect.get('planet2', '?')} (orb: {aspect.get('orb', '?')})\n"
                    else:
                        output += "*No aspect data available*\n"

                    output += f"\n---\n*Source: {result.get('source', 'astroseek.com')}*"

                    return output

                except ImportError:
                    return """## ⚠️ Astroseek Integration Not Available

The Astroseek MCP integration requires additional dependencies.

**To enable:**
1. Install: `pip install beautifulsoup4 lxml requests`
2. Restart the application

**Alternative**: Use HERMES built-in calculators in other tabs.
"""
                except Exception as e:
                    return f"""## ❌ Error

**Error Type**: {type(e).__name__}
**Message**: {str(e)}

This is a proof-of-concept web scraping integration.
For reliable chart data, use HERMES built-in calculators or official APIs.
"""

            def fetch_daily_horoscope(sign):
                """Fetch daily horoscope from Astroseek"""
                try:
                    from astroseek_mcp import AstroseekMCP

                    client = AstroseekMCP()
                    result = client.get_daily_horoscope(sign)

                    if "error" in result:
                        return f"""## ⚠️ Daily Horoscope Not Available

**Note**: {result.get('note', result['error'])}

**Alternative**: {result.get('alternative', 'Use the Chart Calculator above to get personalized transit information.')}

For general daily horoscopes, consider:
- [Astrology.com](https://www.astrology.com/horoscope/daily/)
- [Horoscope.com](https://www.horoscope.com/)
- [AstroStyle](https://astrostyle.com/horoscopes/daily/)
"""

                    return f"""## πŸ“– Daily Horoscope for {sign}

**Date**: {result.get('date', 'Today')}

{result.get('horoscope', 'Horoscope text not available')}

---
*Source: {result.get('source', 'astroseek.com')}*

⚠️ **Disclaimer**: This is fetched from Astroseek.com for demonstration purposes.
Traditional Hellenistic astrology uses natal charts and time-lord techniques (see other tabs) rather than sun-sign horoscopes.
"""

                except ImportError:
                    return "⚠️ Astroseek integration requires beautifulsoup4, lxml, and requests packages."
                except Exception as e:
                    return f"❌ Error: {str(e)}"

            astro_chart_btn.click(
                fn=fetch_astroseek_chart,
                inputs=[astro_date, astro_time, astro_city, astro_country],
                outputs=astro_output
            )

            astro_horoscope_btn.click(
                fn=fetch_daily_horoscope,
                inputs=astro_sign,
                outputs=astro_output
            )

            gr.Markdown("""
            ---
            ### πŸ”§ About This Integration

            **What it does:**
            - Fetches chart data from Astroseek.com
            - Demonstrates MCP integration with external services
            - Shows how HERMES can connect to third-party APIs

            **Limitations:**
            - Web scraping (not an official API)
            - Requires internet connection
            - May break if Astroseek changes HTML
            - Rate limited (1 request/second)
            - Subject to Astroseek's terms of service

            **Better Alternatives:**
            - Use HERMES built-in calculators (other tabs)
            - Swiss Ephemeris via pyswisseph (included)
            - Astro.com API (official)
            - AstroDienst API

            **Why include this?**
            This demonstrates HERMES can integrate with external chart services through the MCP protocol,
            showing architectural flexibility for the MCP Birthday Hackathon.

            For actual chart analysis, use the HERMES calculators in the other tabs!
            """)

        with gr.Tab("ℹ️ About"):
            gr.Markdown("""
            ## About HERMES

            **Hellenistic Ephemeris Research & MCP Educational System**

            ### Purpose
            HERMES is a research and teaching tool for traditional Hellenistic astrology, bridging
            2000-year-old wisdom with modern AI technology.
            
            ### Technical Stack
            - **Agent Framework**: OpenAI GPT-4 + Anthropic Claude
            - **Teaching**: Text-based AI explanations
            - **MCP Server**: Python + Modal (serverless) βœ… **DEPLOYED**
            - **UI**: Gradio 5.49+ on HuggingFace Spaces
            - **Ephemeris**: Swiss Ephemeris (pyswisseph)

            ### MCP Server Features (Modal Serverless)
            The HERMES MCP server is deployed on Modal with 6 serverless functions:
            - `calculate_zodiacal_releasing` - Time-lord periods from Vettius Valens
            - `calculate_firdaria` - Persian time-lord system
            - `get_bound_ruler` - Egyptian bounds (terms)
            - `get_decan_ruler` - Decans (faces)
            - `calculate_full_dignities` - Complete essential dignity analysis
            - `find_fixed_stars` - Fixed star conjunction database

            **Live at**: `modal.com/apps/aamanlamba/hermes-astrology-mcp`

            ### Interactive Features
            - Essential dignity calculations (domicile, exaltation, triplicity, bounds, decans)
            - Time-lord systems (annual profections, zodiacal releasing)
            - Traditional lot calculations (Fortune, Spirit with sect consideration)
            - Source research with citations to ancient texts
            - AI-powered teaching explanations
            
            ### Educational Use Cases
            1. **Students**: Interactive learning of complex traditional techniques
            2. **Researchers**: Rapid comparison across source texts and translations
            3. **Practitioners**: Chart analysis using authentic Hellenistic methods
            
            ### Built For
            MCP 1st Birthday Hackathon (Nov 14-30, 2025)
            
            ### Author
            Created by an astrology author and strategy consultant
            
            ### Credits & Acknowledgments

            **Hackathon Sponsors:**
            - Anthropic, OpenAI, ElevenLabs, Modal, HuggingFace

            **Ancient Sources:**
            - Vettius Valens (*Anthology*, 2nd century CE)
            - Claudius Ptolemy (*Tetrabiblos*, 2nd century CE)
            - Dorotheus of Sidon (*Carmen Astrologicum*, 1st century CE)
            - Firmicus Maternus, Paulus Alexandrinus, Rhetorius

            **Modern Teachers & Resources:**
            - **Chris Brennan** - [*Hellenistic Astrology: The Study of Fate and Fortune*](https://www.hellenisticastrology.com/book/)
              - The definitive modern text on Hellenistic astrology
              - Host of [The Astrology Podcast](https://theastrologypodcast.com)
              - Courses and resources at [HellenisticAstrology.com](https://www.hellenisticastrology.com)
            - **Demetra George** - Traditional astrology teacher and author
            - **Robert Schmidt** - Project Hindsight founder, translator of ancient texts

            Special thanks to Chris Brennan for preserving and teaching these ancient techniques to modern practitioners.

            ---

            ## πŸ“š Primary Ancient Sources

            All techniques in HERMES are based on authentic ancient texts:

            ### Hellenistic Era (1st-7th century CE)
            - **Vettius Valens** (*Anthology*, 2nd century CE) - Our primary source for profections, zodiacal releasing, and lots
            - **Claudius Ptolemy** (*Tetrabiblos*, 2nd century CE) - Theoretical foundations of essential dignities and sect
            - **Dorotheus of Sidon** (*Carmen Astrologicum*, 1st century CE) - Early treatment of time-lord techniques
            - **Paulus Alexandrinus** (*Introductory Matters*, 4th century CE) - Teaching manual with profections
            - **Firmicus Maternus** (*Mathesis*, 4th century CE) - Late Hellenistic synthesis
            - **Rhetorius of Egypt** (6th-7th century CE) - Compilation and commentary on earlier authors

            ### Modern Translations & Commentary
            - **Robert Schmidt** - Project Hindsight translations from Greek and Latin
            - **Chris Brennan** - *Hellenistic Astrology: The Study of Fate and Fortune* (2017) - Comprehensive modern synthesis
            - **Demetra George** - *Ancient Astrology in Theory and Practice* (2019) - Practical application guide

            ### Technique Sources
            - **Domicile, Exaltation, Triplicity** β†’ Ptolemy (*Tetrabiblos* I.17-21), Valens (*Anthology* passim)
            - **Egyptian Bounds** β†’ Preserved in Valens and Paulus (distinct from Ptolemy's system)
            - **Decans (Faces)** β†’ Attributed to Egyptian sources, preserved by Hellenistic authors
            - **Lots (Fortune, Spirit)** β†’ Valens (*Anthology* III, IV), Paulus (*Introductory Matters*)
            - **Annual Profections** β†’ Valens (*Anthology* IV), Paulus (*Introductory Matters* 23)
            - **Zodiacal Releasing** β†’ Valens (*Anthology* IV.4-11) - detailed treatment of "Loosing of the Bond"
            - **Sect Theory** β†’ Valens (*Anthology* III.2), Ptolemy (*Tetrabiblos* III.2)

            ### Why These Sources Matter
            Unlike modern psychological astrology, Hellenistic astrology is a **reconstructed tradition** based on
            ancient texts that were lost for centuries. Thanks to Project Hindsight (1990s-2000s) and modern scholars,
            we can now practice astrology as the Greeks and Romans did - with time-lord techniques, essential dignities,
            and a focus on prediction rather than personality.

            HERMES aims to make these authentic ancient techniques accessible through modern AI technology.

            ---

            *Built with ❀️ for traditional astrology and the MCP Birthday Hackathon*

            *"The stars incline, they do not compel" - Traditional maxim*
            """)
    
    return demo

# Launch the app
if __name__ == "__main__":
    demo = create_demo()
    demo.launch()