Spaces:
Sleeping
Sleeping
File size: 6,256 Bytes
153f125 98fa13f 153f125 98fa13f 153f125 |
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 |
import pandas as pd
from langchain_community.tools import DuckDuckGoSearchRun, TavilySearchResults
from langchain_core.tools import tool
from langchain.schema import HumanMessage, AIMessage, SystemMessage
from langchain_google_genai import ChatGoogleGenerativeAI
import base64
#LLMs
google_llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-lite')
#IMAGE_TOOLS
@tool
def extract_text(img_path: str) -> str:
"""
Extract text from an image file using a multimodal model.
Args:
img_path: A local image file path (strings).
Returns:
A single string containing the concatenated text extracted from each image.
"""
all_text = ""
try:
# Read image and encode as base64
with open(img_path, "rb") as image_file:
image_bytes = image_file.read()
image_base64 = base64.b64encode(image_bytes).decode("utf-8")
# Prepare the prompt including the base64 image data
message = [
HumanMessage(
content=[
{
"type": "text",
"text": (
"Extract all the text from this image. "
"Return only the extracted text, no explanations."
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_base64}"
},
},
]
)
]
# Call the vision-capable model
response = google_llm.invoke(message)
# Append extracted text
all_text += response.content + "\n\n"
return all_text.strip()
except Exception as e:
# You can choose whether to raise or just return an empty string / error message
error_msg = f"Error extracting text: {str(e)}"
print(error_msg)
return ""
@tool
def describe_image(img_path: str) -> str:
"""
Takes an image file path or URL and returns a detailed description of the image.
Args:
image_path_or_url (str): Local file path or URL to the image.
Returns:
str: A detailed description of the image content.
"""
all_text = ""
try:
# Read image and encode as base64
with open(img_path, "rb") as image_file:
image_bytes = image_file.read()
image_base64 = base64.b64encode(image_bytes).decode("utf-8")
# Prepare the prompt including the base64 image data
message = [
HumanMessage(
content=[
{
"type": "text",
"text": (
"Provide a detailed description from this image. "
"Return descriptive text only."
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_base64}"
},
},
]
)
]
# Call the vision-capable model
response = google_llm.invoke(message)
# Append extracted text
all_text += response.content + "\n\n"
return all_text.strip()
except Exception as e:
# You can choose whether to raise or just return an empty string / error message
error_msg = f"Error extracting text: {str(e)}"
print(error_msg)
return ""
#AUDIO_TOOLS
@tool
def transcribe_audio(audio_path: str) -> str:
"""
Transcribe audio from a file using a multimodal model.
Args:
audio_path: A local audio file path (strings).
Returns:
A single string containing the transcribed text.
"""
all_text = ""
try:
# Read audio and encode as base64
with open(audio_path, "rb") as audio_file:
audio_bytes = audio_file.read()
audio_base64 = base64.b64encode(audio_bytes).decode()
# Prepare the prompt including the base64 image data
message = [
HumanMessage(
content=[
{
"type": "text",
"text": (
"Transcribe the following audio input:"
),
},
{
"type": "input_audio",
"input_audio": {
"data": audio_base64,
"format": "wav"
},
},
]
)
]
# Call the vision-capable model
response = google_llm.invoke(message)
# Append extracted text
all_text += response.content + "\n\n"
return all_text.strip()
except Exception as e:
# You can choose whether to raise or just return an empty string / error message
error_msg = f"Error transcribing audio: {str(e)}"
print(error_msg)
return ""
#WEB_SEARCH_TOOL
@tool
def web_search(query: str) -> str:
"""Perform a web search and return the top 5 results."""
#search_tool = DuckDuckGoSearchRun()
search_tool = TavilySearchResults(searxch_depth='basic')
result = search_tool.invoke(query)
return result
#FILE_PARSE_TOOL
@tool
def read_file(file_path: str) -> str:
"""
Reads a text based file and returns its content as a string.
Args:
file_path (str): The path to the file.
Returns:
str: The content of the file.
"""
if file_path.endswith('.txt'):
with open(file_path, 'r') as file:
return file.read()
elif file_path.endswith('.csv'):
return pd.read_csv(file_path).to_string()
elif file_path.endswith('.xlsx'):
return pd.read_excel(file_path).to_string()
elif file_path.endswith('.py'):
with open(file_path, 'r') as file:
return file.read()
else:
raise ValueError("Unsupported file format. Only .txt, .csv, and .xlsx are supported.")
|