File size: 41,326 Bytes
d0490ec
6efe12c
d0490ec
8e63348
 
 
872fb01
d0490ec
 
575233a
e93cb13
e946b39
4697ce0
c803551
ae4a304
eae276f
 
0b83ba2
6efe12c
d0490ec
 
 
6efe12c
d0490ec
d62ee7c
 
ae4a304
 
6efe12c
d0490ec
6efe12c
d0490ec
0b83ba2
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
0b83ba2
d0490ec
 
 
6efe12c
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
6efe12c
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6efe12c
d0490ec
 
e946b39
d0490ec
 
6efe12c
d0490ec
e946b39
d0490ec
 
 
eae276f
d0490ec
 
 
eae276f
4cad7a4
eae276f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da2d730
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4697ce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eae276f
 
4697ce0
 
da2d730
c803551
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cad7a4
c803551
 
 
 
 
 
 
 
 
 
8e63348
 
 
eae276f
8e63348
4cad7a4
 
8e63348
eae276f
872fb01
 
0b83ba2
 
 
 
872fb01
 
 
 
 
eae276f
8e63348
 
 
eae276f
 
 
 
 
 
 
 
 
8e63348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eae276f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e63348
 
eae276f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c803551
8e63348
eae276f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0490ec
 
 
f3b56d3
 
eae276f
0b83ba2
 
 
 
f3b56d3
 
 
 
 
 
 
da2d730
 
4697ce0
0b83ba2
 
c803551
0b83ba2
eae276f
f3b56d3
d0490ec
 
 
 
75c9b07
d0490ec
 
75c9b07
d0490ec
b18b7b9
e459d5d
b18b7b9
 
 
d0490ec
0b83ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
eae276f
b18b7b9
bed3176
b18b7b9
 
 
d0490ec
0b83ba2
b18b7b9
8e63348
0b83ba2
4cad7a4
75c9b07
0b83ba2
 
 
d0490ec
75c9b07
 
4697ce0
75c9b07
d0490ec
75c9b07
d0490ec
75c9b07
d0490ec
75c9b07
d0490ec
75c9b07
d0490ec
75c9b07
 
4697ce0
75c9b07
 
d0490ec
75c9b07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0490ec
 
 
ae4a304
e93cb13
47d092c
4697ce0
d0490ec
2948a14
ead2a02
6efe12c
e946b39
da2d730
ae4a304
bb4d19c
da2d730
eae276f
0a04e0d
da2d730
ae4a304
d0490ec
 
 
 
e946b39
 
556e783
 
e946b39
ae4a304
e946b39
4cad7a4
8e63348
 
43c174f
e946b39
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4a304
 
 
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
095cb52
 
 
d0490ec
 
 
 
 
 
 
 
 
 
 
6efe12c
 
d0490ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
095cb52
 
02bdc0b
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
import os
import gradio as gr
import requests
import tempfile
import mimetypes
import base64
import json
import pandas as pd
import datetime
from langchain.tools import tool
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
from langchain.agents import initialize_agent, AgentType
from bs4 import BeautifulSoup
import base64
from langchain_openai import ChatOpenAI
import fitz
import yt_dlp
import re

## # Load environment variables from .env file
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

# Load the environment variables
HF_ACCESS_KEY = os.getenv('HF_ACCESS_KEY')
WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
OPENAI_KEY = os.getenv('OPENAI_KEY')
OPENAI_MODEL = os.getenv ('OPENAI_MODEL')

########## ----- DEFINING TOOLS -----##########

# --- TOOL 1: Web Search Tool (DuckDuckGo) ---

@tool
def search_tool(query: str) -> str:
    """Answer general knowledge or current events queries using DuckDuckGo."""
    url = f"https://api.duckduckgo.com/?q={query}&format=json&no_html=1"
    try:
        resp = requests.get(url, timeout=20)
        resp.raise_for_status()
        data = resp.json()
        for key in ["AbstractText", "Answer", "Definition"]:
            if data.get(key):
                return data[key].split(".")[0]
        return "no_answer"
    except Exception:
        return "error"

# when you use the @tool decorator from langchain.tools, the tool.name and tool.description are automatically extracted from your function
# tool.name is set to the function name (e.g., `search_tool`), and 
# tool.description is set to the docstring of the function  (the triple-quoted string right under def ...) (e.g., "Answer general knowledge or current events queries using DuckDuckGo.").

# --- TOOL 2: Weather Tool (OpenWeatherMap) ---
@tool
def get_weather(city: str) -> str:
    """Get current temperature in Celsius for a city."""
    import os
    api_key = os.environ.get("WEATHER_API_KEY")
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"
    try:
        resp = requests.get(url, timeout=20)
        resp.raise_for_status()
        data = resp.json()
        return str(round(data["main"]["temp"]))
    except Exception:
        return "error"

# --- TOOL 3: Calculator Tool ---
@tool
def calculator(expression: str) -> str:
    """Evaluate math expressions."""
    try:
        allowed = "0123456789+-*/(). "
        if not all(c in allowed for c in expression):
            return "error"
        result = eval(expression, {"__builtins__": None}, {})
        return str(result)
    except Exception:
        return "error"
    
# --- TOOL 4: Unit Conversion Tool ---
@tool
def convert_units(args: str) -> str:
    """
    Convert between metric and imperial units (length, mass, temperature).
    Input format: '<value> <from_unit> to <to_unit>', e.g. '10 meters to feet'
    """
    try:
        parts = args.lower().split()
        value = float(parts[0])
        from_unit = parts[1]
        to_unit = parts[3]
        conversions = {
            ("meters", "feet"): lambda v: v * 3.28084,
            ("feet", "meters"): lambda v: v / 3.28084,
            ("kg", "lb"): lambda v: v * 2.20462,
            ("lb", "kg"): lambda v: v / 2.20462,
            ("celsius", "fahrenheit"): lambda v: v * 9/5 + 32,
            ("fahrenheit", "celsius"): lambda v: (v - 32) * 5/9,
        }
        func = conversions.get((from_unit, to_unit))
        if func:
            return str(round(func(value), 2))
        return "error"
    except Exception:
        return "error"

# --- TOOL 5: Date & Time Tool ---
@tool
def get_time(input: str) -> str:
    """Get current UTC time as HH:MM."""
    return datetime.datetime.utc().strftime("%H:%M")

@tool
def get_date(input: str) -> str:
    """Get current date as YYYY-MM-DD."""
    return datetime.datetime.utc().strftime("%Y-%m-%d")


# --- TOOL 6: Wikipedia Summary Tool ---
@tool
def wikipedia_summary(query: str) -> str:
    """
    Answer questions from Wikipedia related to world information, facts, sports, olympics, history, facts, general knowledge etc. 
    """

    # Heuristic: If the query looks data-driven, extract tables/lists
    data_keywords = [
        "list", "table", "which", "who", "how many", "after", "before", "country", "year", "wikipedia", "winners", "recipients", "participants", "awards", "nationality", "film", "olympics", "sports", "statistics", "events", "year", "rankings"
    ]
    if any(word in query.lower() for word in data_keywords):
        # Step 1: Search Wikipedia for the most relevant page
        search_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "query",
            "list": "search",
            "srsearch": query,
            "format": "json"
        }
        try:
            resp = requests.get(search_url, params=params, timeout=15)
            resp.raise_for_status()
            results = resp.json().get("query", {}).get("search", [])
            if not results:
                return "no_answer"
            page_title = results[0]["title"]
            page_url = f"https://en.wikipedia.org/wiki/{page_title.replace(' ', '_')}"
        except Exception:
            return "error: Could not search Wikipedia"

        # Step 2: Fetch the Wikipedia page and extract tables/lists
        try:
            page_resp = requests.get(page_url, timeout=20)
            page_resp.raise_for_status()
            soup = BeautifulSoup(page_resp.text, "html.parser")
            output = f"Source: {page_url}\n"

            # Extract all tables with relevant columns
            tables = soup.find_all("table", {"class": ["wikitable", "sortable"]})
            found_table = False
            for table in tables:
                table_str = str(table)
                if any(word in table_str.lower() for word in ["winner", "name", "year", "nationality", "country", "recipient", "team"]):
                    try:
                        df = pd.read_html(table_str)[0]
                        output += "\n--- Extracted Table ---\n"
                        output += df.to_csv(index=False)
                        found_table = True
                    except Exception:
                        continue

            # If no relevant table, extract lists
            if not found_table:
                lists = soup.find_all(['ul', 'ol'])
                for lst in lists:
                    items = lst.find_all('li')
                    if len(items) > 2:
                        output += "\n--- Extracted List ---\n"
                        for item in items:
                            text = item.get_text(separator=" ", strip=True)
                            output += f"{text}\n"
                        break

            # Fallback: return the first paragraph if nothing else
            if not found_table and "--- Extracted List ---" not in output:
                first_p = soup.find("p")
                output += first_p.get_text(strip=True)[:500] if first_p else "no_answer"

            # Limit output length for LLM context
            return output[:3500]
        except Exception as e:
            return f"error: {e}"

    # Otherwise, just return the summary as before
    url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query.replace(' ', '_')}"
    try:
        resp = requests.get(url, timeout=20)
        resp.raise_for_status()
        data = resp.json()
        return data.get("extract", "no_answer").split(".")[0]
    except Exception:
        return "error"

# --- TOOL 7: Dictionary Tool ---
@tool
def dictionary_lookup(word: str) -> str:
    """Get the definition of an English word."""
    url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}"
    try:
        resp = requests.get(url, timeout=20)
        resp.raise_for_status()
        data = resp.json()
        return data[0]["meanings"][0]["definitions"][0]["definition"]
    except Exception:
        return "error"
    
# --- TOOL 8: Currency Conversion Tool ---
@tool
def currency_convert(args: str) -> str:
    """
    Convert an amount from one currency to another.
    Input format: '<amount> <from_currency> to <to_currency>', e.g. '100 USD to EUR'
    """
    try:
        parts = args.upper().split()
        amount = float(parts[0])
        from_currency = parts[1]
        to_currency = parts[3]
        url = f"https://api.exchangerate.host/convert?from={from_currency}&to={to_currency}&amount={amount}"
        resp = requests.get(url, timeout=20)
        resp.raise_for_status()
        data = resp.json()
        return str(round(data["result"], 2))
    except Exception:
        return "error"

# --- TOOL 9: Image Captioning Tool ---
@tool
def image_caption(image_url: str) -> str:
    """Generate a descriptive caption for an image given its URL."""
    api_url = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-base"
    headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}
    payload = {"inputs": image_url}
    try:
        resp = requests.post(api_url, headers=headers, json=payload, timeout=30)
        resp.raise_for_status()
        data = resp.json()
        return data[0]["generated_text"] if isinstance(data, list) else data.get("generated_text", "no_caption")
    except Exception:
        return "error"
    
# --- TOOL 10: Optical Character Recognition (OCR) Tool ---
@tool
def ocr_image(image_url: str) -> str:
    """Extract text from an image given its URL."""
    api_url = "https://api-inference.huggingface.co/models/impira/layoutlm-document-qa"
    headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}
    payload = {"inputs": {"image": image_url, "question": "What text is in the image?"}}
    try:
        resp = requests.post(api_url, headers=headers, json=payload, timeout=30)
        resp.raise_for_status()
        data = resp.json()
        return data.get("answer", "no_text_found")
    except Exception:
        return "error"
    
# --- TOOL 11: Image Classification Tool ---
@tool
def classify_image(image_url: str) -> str:
    """Classify the main object or scene in an image given its URL."""
    api_url = "https://api-inference.huggingface.co/models/google/vit-base-patch16-224"
    headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}
    payload = {"inputs": image_url}
    try:
        resp = requests.post(api_url, headers=headers, json=payload, timeout=30)
        resp.raise_for_status()
        data = resp.json()
        return data[0]["label"] if isinstance(data, list) else data.get("label", "no_label")
    except Exception:
        return "error"

# --- TOOL 12: Web Scraping Tool ---
@tool
def web_scrape_tool(url: str) -> str:
    """
    Scrape the main textual content from a given website URL and return a concise summary or answer.
    Input: A valid URL (e.g., 'https://en.wikipedia.org/wiki/Python_(programming_language)')
    """
    try:
        headers = {
            "User-Agent": "Mozilla/5.0 (compatible; WebScrapeTool/1.0)"
        }
        resp = requests.get(url, headers=headers, timeout=20)
        resp.raise_for_status()
        soup = BeautifulSoup(resp.text, "html.parser")
        # Try to extract main content from common tags
        paragraphs = soup.find_all("p")
        text = " ".join(p.get_text() for p in paragraphs)
        # Limit to first 2000 characters for brevity
        return text[:2000] if text else "No textual content found."
    except Exception as e:
        return f"error: {e}"

# --- TOOL 13: Audio to Text Transcription Tool ---
@tool
def audio_to_text(audio_url: str) -> str:
    """
    Transcribe speech from an audio file URL to text using Hugging Face's Whisper model.
    Input: A direct link to an audio file (e.g., .mp3, .wav).
    Output: The transcribed text.
    """
    api_url = "https://api-inference.huggingface.co/models/openai/whisper-large-v3"
    headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}
    try:
        # Download the audio file
        audio_resp = requests.get(audio_url, timeout=30)
        audio_resp.raise_for_status()
        audio_bytes = audio_resp.content
        # Encode audio as base64 for API
        audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
        payload = {
            "inputs": audio_b64,
            "parameters": {"return_timestamps": False}
        }
        resp = requests.post(api_url, headers=headers, json=payload, timeout=60)
        resp.raise_for_status()
        data = resp.json()
        return data.get("text", "no_answer")
    except Exception as e:
        return f"error: {e}"

# --- TOOL 14: Python Code Executor Tool ---
@tool
def python_executor(code: str) -> str:
    """
    Safely execute simple Python code and return the result if the code is in the question. If the question has .py file attached, use 'python_excel_audio_video_attached_file_tool' tool first.
    Only supports expressions and basic statements (no imports, file I/O, or system access).
    """
    try:
        # Restrict built-ins for safety
        allowed_builtins = {"abs": abs, "min": min, "max": max, "sum": sum, "len": len, "range": range}
        # Only allow expressions, not statements
        result = eval(code, {"__builtins__": allowed_builtins}, {})
        return str(result)
    except Exception as e:
        return f"error: {e}"

# --- TOOL 15: Attachment Processing Tool ---
@tool
def python_excel_audio_video_attached_file_tool(input_str: str) -> str:
    """
    Processes an input attachment (audio, image, video, Excel, or Python .py file) and returns extracted text or a summary suitable for LLM input.
    This function accepts a JSON string 'input_str' with keys: 'file_bytes' (base64), and 'filename'. So input the file and filename as json strings. For unsupported file types the function returns an error message.
    """
    import pandas as pd

    try:
        # Extract only the JSON object from the input string
        match = re.search(r'(\{.*\})', input_str, re.DOTALL)
        if match:
            input_str = match.group(1)
        data = json.loads(input_str)
        file_bytes = base64.b64decode(data["file_bytes"])
        filename = data["filename"]
    except Exception as e:
        return f"error: {e}"

    # Detect file type
    mime_type, _ = mimetypes.guess_type(filename)
    if not mime_type:
        # Fallback for .py and .csv files
        if filename.lower().endswith(".py"):
            mime_type = "text/x-python"
        elif filename.lower().endswith(".csv"):
            mime_type = "text/csv"
        elif filename.lower().endswith((".xls", ".xlsx")):
            mime_type = "application/vnd.ms-excel"
        else:
            return "error: Could not determine file type. Skip the file"

    # Handle audio files
    if mime_type.startswith("audio"):
        api_url = "https://api-inference.huggingface.co/models/openai/whisper-large-v3"
        headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}
        files = {"file": (filename, file_bytes)}
        try:
            resp = requests.post(api_url, headers=headers, files=files, timeout=60)
            resp.raise_for_status()
            data = resp.json()
            transcript = data.get("text", "")
            if transcript:
                return f"Transcript of the audio: {transcript}"
            else:
                return "error: No transcript returned."
        except Exception as e:
            return f"error: {e}"

    # Handle image files
    elif mime_type.startswith("image"):
        image_b64 = base64.b64encode(file_bytes).decode()
        return f"Attached image (base64): {image_b64}"

    # Handle video files (extract audio, then transcribe)
    elif mime_type.startswith("video"):
        try:
            with tempfile.NamedTemporaryFile(delete=False, suffix=filename.split('.')[-1]) as tmp_video:
                tmp_video.write(file_bytes)
                tmp_video.flush()
                video_path = tmp_video.name

            audio_path = video_path + ".wav"
            import subprocess
            subprocess.run([
                "ffmpeg", "-i", video_path, "-vn", "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1", audio_path
            ], check=True)

            with open(audio_path, "rb") as f:
                audio_bytes = f.read()

            api_url = "https://api-inference.huggingface.co/models/openai/whisper-large-v3"
            headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}
            files = {"file": ("audio.wav", audio_bytes)}
            resp = requests.post(api_url, headers=headers, files=files, timeout=120)
            resp.raise_for_status()
            data = resp.json()
            transcript = data.get("text", "")
            if transcript:
                return f"Transcript of the video audio: {transcript}"
            else:
                return "error: No transcript returned from video audio."
        except Exception as e:
            return f"error: {e}"

    # Handle Excel files (.xls, .xlsx, .csv)
    elif mime_type in ["application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/csv"]:
        try:
            with tempfile.NamedTemporaryFile(delete=False, suffix=filename.split('.')[-1]) as tmp_excel:
                tmp_excel.write(file_bytes)
                tmp_excel.flush()
                excel_path = tmp_excel.name

            if filename.lower().endswith(".csv"):
                df = pd.read_csv(excel_path)
                preview = df.head(500).to_csv(index=False)
                return f"CSV file preview (first 5 rows):\n{preview}"
            else:
                xl = pd.ExcelFile(excel_path)
                sheet_names = xl.sheet_names
                preview = ""
                for sheet in sheet_names:
                    df = xl.parse(sheet)
                    preview += f"\nSheet: {sheet}\n{df.head(500).to_csv(index=False)}"
                return f"Excel file sheets: {sheet_names}\nPreview (first 3 rows per sheet):{preview}"
        except Exception as e:
            return f"error: {e}"

    # Handle Python files (.py)
    elif mime_type == "text/x-python" or filename.lower().endswith(".py"):
        try:
            code = file_bytes.decode("utf-8", errors="replace")
            lines = code.splitlines()
            preview = "\n".join(lines[:40])
            return f"Python file preview (first 40 lines):\n{preview}"
        except Exception as e:
            return f"error: {e}"

    else:
        return "error: Unsupported file type. Please skip the file usage."

    

# --- TOOL 16: Research Paper Info Extraction Tool ---
@tool
def search_and_extract_research_paper_info(query: str) -> str:
    """
    Searches for research papers using the Semantic Scholar API, downloads the top result's PDF,
    and extracts the title, authors, abstract, and main sections.
    Input: A search query (e.g., topic, paper title, or keywords).
    Output: A summary with title, authors, abstract, and main sections from the top result.
    """
    try:
        # Search for papers using Semantic Scholar API
        search_url = "https://api.semanticscholar.org/graph/v1/paper/search"
        params = {
            "query": query,
            "limit": 1,
            "fields": "title,authors,abstract,url,openAccessPdf"
        }
        resp = requests.get(search_url, params=params, timeout=20)
        resp.raise_for_status()
        data = resp.json()
        if not data.get("data"):
            return "No papers found for this query."
        paper = data["data"][0]
        title = paper.get("title", "")
        authors = ", ".join([a["name"] for a in paper.get("authors", [])])
        abstract = paper.get("abstract", "")
        pdf_url = paper.get("openAccessPdf", {}).get("url")
        if not pdf_url:
            return f"Paper found: {title}\nAuthors: {authors}\nAbstract: {abstract}\n(No open access PDF available.)"

        # Download the PDF
        pdf_resp = requests.get(pdf_url, timeout=30)
        pdf_resp.raise_for_status()
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
            tmp_pdf.write(pdf_resp.content)
            tmp_pdf.flush()
            pdf_path = tmp_pdf.name

        # Extract text from PDF
        doc = fitz.open(pdf_path)
        full_text = ""
        for page in doc:
            full_text += page.get_text("text") + "\n"

        # Simple heuristics to extract main sections
        lines = full_text.splitlines()
        main_sections = ""
        in_main = False
        for line in lines:
            if "introduction" in line.lower():
                in_main = True
            if in_main:
                main_sections += line.strip() + " "
                if len(main_sections) > 1000:
                    break

        summary = (
            f"Title: {title}\n"
            f"Authors: {authors}\n"
            f"Abstract: {abstract}\n"
            f"Main Sections (excerpt): {main_sections.strip()}"
        )
        return summary if summary.strip() else "No information extracted."
    except Exception as e:
        return f"error: {e}"
    

# --- TOOL 17:Tool for sports, awards, competitions etc. ---
@tool
def sports_awards_historicalfacts_tool(query: str) -> str:
    """
    For questions about lists, awards, competitions, or historical facts, this tool searches Wikipedia,
    extracts all tables and lists from the most relevant page, and returns them as CSV or plain text.
    This gives the LLM enough context to answer complex queries about people, years, nationalities, etc.
    """

    # Step 1: Search Wikipedia for the most relevant page
    search_url = "https://en.wikipedia.org/w/api.php"
    params = {
        "action": "query",
        "list": "search",
        "srsearch": query,
        "format": "json"
    }
    try:
        resp = requests.get(search_url, params=params, timeout=15)
        resp.raise_for_status()
        results = resp.json().get("query", {}).get("search", [])
        if not results:
            return "no_answer"
        page_title = results[0]["title"]
        page_url = f"https://en.wikipedia.org/wiki/{page_title.replace(' ', '_')}"
    except Exception:
        return "error: Could not search Wikipedia"

    # Step 2: Fetch the Wikipedia page and extract tables and lists
    try:
        page_resp = requests.get(page_url, timeout=20)
        page_resp.raise_for_status()
        soup = BeautifulSoup(page_resp.text, "html.parser")
        output = f"Source: {page_url}\n"

        # Extract all tables with relevant columns
        tables = soup.find_all("table", {"class": ["wikitable", "sortable"]})
        found_table = False
        for table in tables:
            table_str = str(table)
            if any(word in table_str.lower() for word in ["winner", "name", "year", "nationality", "country"]):
                try:
                    df = pd.read_html(table_str)[0]
                    output += "\n--- Extracted Table ---\n"
                    output += df.to_csv(index=False)
                    found_table = True
                except Exception:
                    continue

        # If no relevant table, extract lists (e.g., <ul> or <ol> with <li>)
        if not found_table:
            lists = soup.find_all(['ul', 'ol'])
            for lst in lists:
                items = lst.find_all('li')
                if len(items) > 2:  # Only consider lists with more than 2 items
                    output += "\n--- Extracted List ---\n"
                    for item in items:
                        text = item.get_text(separator=" ", strip=True)
                        output += f"{text}\n"
                    break  # Only include the first relevant list

        # Fallback: return the first paragraph if nothing else
        if not found_table and "--- Extracted List ---" not in output:
            first_p = soup.find("p")
            output += first_p.get_text(strip=True)[:500] if first_p else "no_answer"

        # Limit output length for LLM context
        return output[:3500]
    except Exception as e:
        return f"error: {e}"

# --- TOOL 18: YouTube Transcript Tool ---
@tool
def audio_video_url_transcript_tool(youtube_url: str) -> str:
    """
    Given a URL about video or audio, like YouTube video URL, download the audio and return a transcript using Whisper.
    """
    api_url = "https://api-inference.huggingface.co/models/openai/whisper-large-v3"
    headers = {"Authorization": f"Bearer {HF_ACCESS_KEY}"}

    try:
        # Download audio from YouTube
        with tempfile.TemporaryDirectory() as tmpdir:
            ydl_opts = {
                'format': 'bestaudio/best',
                'outtmpl': f'{tmpdir}/audio.%(ext)s',
                'quiet': True,
                'noplaylist': True,
                'extractaudio': True,
                'audioformat': 'wav',
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'wav',
                    'preferredquality': '192',
                }],
            }
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(youtube_url, download=True)
                audio_path = ydl.prepare_filename(info).rsplit('.', 1)[0] + '.wav'

            # Read audio bytes
            with open(audio_path, "rb") as f:
                audio_bytes = f.read()

        # Encode audio as base64 for API
        audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
        payload = {
            "inputs": audio_b64,
            "parameters": {"return_timestamps": False}
        }
        resp = requests.post(api_url, headers=headers, json=payload, timeout=120)
        resp.raise_for_status()
        data = resp.json()
        return data.get("text", "no_answer")
    except Exception as e:
        return f"error: {e}"
    
##-- Tool Discovery ---
# Use @tool for each function.
# Use get_all_tools() to auto-discover all decorated tools.
# tools_list = get_all_tools()
tools_list = [
    python_excel_audio_video_attached_file_tool,
    wikipedia_summary,
    sports_awards_historicalfacts_tool,
    search_and_extract_research_paper_info,
    python_executor,
    get_weather,
    calculator,
    convert_units,
    get_time,
    get_date,
    dictionary_lookup,
    currency_convert,
    image_caption,
    ocr_image,
    classify_image,
    search_tool,
    web_scrape_tool,
    audio_to_text, 
    # sports_awards_historicalfacts_tool,
    audio_video_url_transcript_tool
]

tool_descriptions = "\n".join(f"- {tool.name}: {tool.description}" for tool in tools_list)



## --
# --- System Prompt for the Agent ---

system_prompt = f"""
You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: [YOUR FINAL ANSWER]. 
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings, preferably not more than two lines.
If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. 
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. 
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.

For each question, follow this format:

Question: the input question you must answer
Thought: your reasoning about what to do next
Action: the action to take, must be one of the tools. If no relevant tools, answer the question directly.
Action Input: the input to the action
Observation: the result of the action
... (repeat Thought/Action/Action Input/Observation as needed)
Final Answer: the answer to the original question, as concise as possible (number, short string, or comma-separated list, no extra explanation).

Rules for YOUR FINAL ANSWER:
If the questions is about 'how many' or 'how many times' or 'how many years' or 'how many people' or 'how many items' or 'how many albums' or 'how many songs' (basically needing quantitative reply), then YOUR FINAL ANSWER should be a number.
If the question is about 'what', 'who', 'where', 'when', 'which', 'why', 'how' or similar, then YOUR FINAL ANSWER should be a short string or a comma separated list of strings.

You also have access to a set of tools, which you can use to answer the question. The available tools with their descriptions are:
{tool_descriptions}

If there is a file (image, audio, or video) attached to the question, you should use the process_attachment tool to process it and follow the instructions below:
 - For audio or video attachments, the process_attachment tool will transcribe the audio and return the transcript, which you can use to answer the question. 
 -  For image attachments, the process_attachment tool will return a base64 encoded string of the image. You can use this encoded information to provide answer.

If the question is related to sports, awards, historical facts or similar topic that can be answered from wikipedia, you should use the 'sports_awards_historicalfacts_tool' or if the question is similar or related that can be searched in wikipedia, use the more specific tool 'wikipedia_summary' to fetch relevant page information and answer from it. 
In general, you must use tools only if needed for the question and only if the question can be answered by one of the provided tools. Otherwise provide the answer based on your knowledge. You must not use multiple tools in a single call. Don't hallucinate.

If after 3 to 4 iterations also a tool usage is not useful then try to answer directly based on your knowledge. If you cannot answer, respond with "no_answer".

"""
# If your final answer is something like 'there were 5 studio albums published between 2000 and 2009' then modify YOUR FINAL ANSWER as: '5' 
# If your final answer is something like 'b, e' then YOUR FINAL ANSWER be: 'b, e'


# system_prompt = f"""
# You are an intelligent assistant with access to the following tools:

# {tool_descriptions}

# For every question, you must do your internal reasoning using the Thought → Action → Observation → Answer process, but your output to the user should be ONLY the final answer as a single value (number, string, or comma-separated list), with no extra explanation, thoughts, actions, or observations.

# **If a tool returns a long text or description (such as from a web scraping tool), you must carefully read and process that output, and extract or identify ONLY the most relevant, concise answer to the user's question, and provide a single string as output. Do not return the full text or irrelevant details.**

# **Your output must be only the answer. Do not include any reasoning, tool calls, or explanations.**

# Examples:

# Q: What is 7 * (3 + 2)?
# Your Output: 35

# Q: What’s the weather in Tokyo?
# Your Output: 22

# Q: What is the capital of France?
# Your Output: Paris

# Q: Which year was python 3.0 released as per the website https://en.wikipedia.org/wiki/Python_(programming_language)?
# (Tool returns a long description about Python.)
# Your Output: 2008

# Q: Convert 10 meters to feet.
# Your Output: 32.81

# Instructions:
# - Always do your internal reasoning (Thought → Action → Observation → Answer) before producing the answer, but DO NOT show this reasoning to the user.
# - Use a tool only if necessary, and don't use multiple tools in a call. Don't use a tool if you can answer directly.
# - Your output must be a single value (number, string, or comma-separated list) with no extra explanation or formatting.
# - If you cannot answer the question or if you couldn't process the input question just answer as "no_answer".
# - Be concise and accurate.
# """

## --- Initialize Hugging Face Model ---
# Generate the chat interface, including the tools
'''
llm = HuggingFaceEndpoint(
    repo_id="meta-llama/Llama-3.3-70B-Instruct",
    # repo_id="Qwen/Qwen2.5-32B-Instruct",
    huggingfacehub_api_token=HF_ACCESS_KEY,
    # model_kwargs={'prompt': system_prompt}
    # system_prompt=system_prompt,
)
chat_llm = ChatHuggingFace(llm=llm)
'''
chat_llm = ChatOpenAI(
    openai_api_key=OPENAI_KEY,
    model_name=OPENAI_MODEL,
    temperature=0.2,
    # max_tokens=10
)

# chat = ChatHuggingFace(llm=llm, verbose=True)
# tools = [search_tool, fetch_weather]
# chat_with_tools = chat.bind_tools(tools)

agent = initialize_agent(
    tools=tools_list,
    # llm=llm,
    llm=chat_llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    agent_kwargs={"system_message": system_prompt},
    verbose=True,
    max_iterations=7, # Increase as needed
    max_execution_time=4000, # Increase as needed
    early_stopping_method="generate",
    handle_parsing_errors=True
)


## --
def run_and_submit_all( profile: gr.OAuthProfile | None):
    """
    Fetches all questions, runs the BasicAgent on them, submits all answers,
    and displays the results.
    """
    # --- Determine HF Space Runtime URL and Repo URL ---
    space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code

    if profile:
        username= f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        print("User not logged in.")
        return "Please Login to Hugging Face with the button.", None

    api_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    """
    # 1. Instantiate Agent ( modify this part to create your agent)
    try:
        agent = BasicAgent()
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None
    # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
    """
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    print(agent_code)

    # 2. Fetch Questions
    print(f"Fetching questions from: {questions_url}")
    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()
        questions_data = response.json()
        if not questions_data:
             print("Fetched questions list is empty.")
             return "Fetched questions list is empty or invalid format.", None
        print(f"Fetched {len(questions_data)} questions.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return f"Error fetching questions: {e}", None
    except requests.exceptions.JSONDecodeError as e:
         print(f"Error decoding JSON response from questions endpoint: {e}")
         print(f"Response text: {response.text[:500]}")
         return f"Error decoding server response for questions: {e}", None
    except Exception as e:
        print(f"An unexpected error occurred fetching questions: {e}")
        return f"An unexpected error occurred fetching questions: {e}", None

    # 3. Run your Agent
    results_log = []
    answers_payload = []
    print(f"Running agent on {len(questions_data)} questions...")
    for item in questions_data:
        task_id = item.get("task_id")
        question_text = item.get("question")
        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue
        try:
            # full_prompt = f"{system_prompt}\n Input Question: {question_text}"
            # submitted_answer = agent.run(full_prompt)
            submitted_answer = agent.run(question_text)
            answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
            results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
        except Exception as e:
             print(f"Error running agent on task {task_id}: {e}")
             results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})

    if not answers_payload:
        print("Agent did not produce any answers to submit.")
        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)

    # 4. Prepare Submission 
    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
    print(status_update)

    # 5. Submit
    print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
    try:
        response = requests.post(submit_url, json=submission_data, timeout=60)
        response.raise_for_status()
        result_data = response.json()
        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        print("Submission successful.")
        results_df = pd.DataFrame(results_log)
        return final_status, results_df
    except requests.exceptions.HTTPError as e:
        error_detail = f"Server responded with status {e.response.status_code}."
        try:
            error_json = e.response.json()
            error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
        except requests.exceptions.JSONDecodeError:
            error_detail += f" Response: {e.response.text[:500]}"
        status_message = f"Submission Failed: {error_detail}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df


# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
    gr.Markdown("# Basic Agent Evaluation Runner")
    gr.Markdown(
        """
        **Instructions:**

        1.  Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
        2.  Log in to your Hugging Face account using the button below. This uses your HF username for submission.
        3.  Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.

        ---
        **Disclaimers:**
        Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
        This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
        """
    )

    gr.LoginButton()
    # login_btn = gr.LoginButton()
    # login_btn.activate()

    run_button = gr.Button("Run Evaluation & Submit All Answers")

    status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
    # Removed max_rows=10 from DataFrame constructor
    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)

    run_button.click(
        fn=run_and_submit_all,
        outputs=[status_output, results_table]
    )

if __name__ == "__main__":
    print("\n" + "-"*30 + " App Starting " + "-"*30)
    # Check for SPACE_HOST and SPACE_ID at startup for information
    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup

    if space_host_startup:
        print(f"✅ SPACE_HOST found: {space_host_startup}")
        print(f"   Runtime URL should be: https://{space_host_startup}.hf.space")
    else:
        print("ℹ️  SPACE_HOST environment variable not found (running locally?).")

    if space_id_startup: # Print repo URLs if SPACE_ID is found
        print(f"✅ SPACE_ID found: {space_id_startup}")
        print(f"   Repo URL: https://huggingface.co/spaces/{space_id_startup}")
        print(f"   Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
    else:
        print("ℹ️  SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")

    print("-"*(60 + len(" App Starting ")) + "\n")

    print("Launching Gradio Interface for Basic Agent Evaluation...")

# Launch the Gradio app
demo.launch(debug=True, share=True) #share=True