Daniel Amendoeira commited on
Commit
77866f8
·
verified ·
1 Parent(s): ffff64a

Update tools.py

Browse files
Files changed (1) hide show
  1. tools.py +51 -1
tools.py CHANGED
@@ -1,5 +1,10 @@
1
  from langchain.tools import Tool
2
  import datetime
 
 
 
 
 
3
 
4
  def current_date(_):
5
  return datetime.datetime.now().strftime("%Y-%m-%d")
@@ -33,4 +38,49 @@ datetime_tools = [
33
  func=days_until,
34
  description="Returns the number of days from today until a given date (input format: YYYY-MM-DD)."
35
  )
36
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from langchain.tools import Tool
2
  import datetime
3
+ import requests
4
+ import openai
5
+ import os
6
+ import tempfile
7
+ from urllib.parse import urlparse
8
 
9
  def current_date(_):
10
  return datetime.datetime.now().strftime("%Y-%m-%d")
 
38
  func=days_until,
39
  description="Returns the number of days from today until a given date (input format: YYYY-MM-DD)."
40
  )
41
+ ]
42
+
43
+ def transcribe_audio(audio_input: str) -> str:
44
+ """
45
+ Transcribes an audio file from a local file or a URL
46
+
47
+ Args:
48
+ audio_input (str): A local file path or a direct URL to the audio file (.mp3, .m4a, etc.)
49
+
50
+ Returns:
51
+ str: The transcribed text from the audio.
52
+ """
53
+ try:
54
+ # Detects if audio_input is a URL
55
+ is_url = audio_input.startswith("http://") or audio_input.startswith("https://")
56
+
57
+ if is_url:
58
+ parsed = urlparse(audio_input) # breaks down the URL into components (scheme, netloc, path, params, etc.)
59
+ path_extracted = os.path.splitext(parsed.path)[1] or ".mp3" # get the actual file extension from the URL path or define it to .mp3 if no extension is found
60
+
61
+ # Download to temporary file
62
+ with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp_file:
63
+ response = requests.get(audio_input)
64
+ response.raise_for_status()
65
+ tmp_file.write(response.content)
66
+ file_path = tmp_file.name
67
+ else:
68
+ file_path = audio_input
69
+
70
+ # Transcribe using OpenAI Whisper
71
+ client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
72
+ with open(file_path, "rb") as audio_file:
73
+ transcription = client.audio.transcriptions.create(
74
+ model="whisper-1",
75
+ file=audio_file
76
+ )
77
+ return transcription.text
78
+
79
+ except Exception as e:
80
+ return f"Transcription failed: {e}"
81
+
82
+ transcribe_audio_tool = Tool(
83
+ name="transcribe_audio",
84
+ func=transcribe_audio,
85
+ description="Transcribes an audio file from a local file or a URL"
86
+ )