mirror of
https://github.com/OS-Copilot/OS-Copilot.git
synced 2026-04-13 03:00:19 -04:00
update API
This commit is contained in:
@@ -33,7 +33,7 @@ def main():
|
||||
parser.add_argument('--config_path', type=str, default='config.json', help='openAI config file path')
|
||||
parser.add_argument('--query', type=str, default=None, help='user query')
|
||||
parser.add_argument('--query_file_path', type=str, default='', help='user query file path')
|
||||
parser.add_argument('--task_id', type=str, default="5e76cfc3-f33d-4416-b8ae-3ef292830207", help='GAIA dataset task_id')
|
||||
parser.add_argument('--task_id', type=str, default="d62cbee6-47c7-4918-825d-3b73b1af7e85", help='GAIA dataset task_id')
|
||||
parser.add_argument('--cache_dir', type=str, default=None, help='GAIA dataset cache dir path')
|
||||
parser.add_argument('--logging_filedir', type=str, default='log/test_level1', help='GAIA dataset cache dir path')
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Calculate the duration of the specified audio file and return the duration in seconds.
|
||||
@@ -0,0 +1 @@
|
||||
Implement Newton's Method to find a root of the function f(x).
|
||||
1
jarvis/action_lib/action_description/read_json_file.txt
Normal file
1
jarvis/action_lib/action_description/read_json_file.txt
Normal file
@@ -0,0 +1 @@
|
||||
Read the content of the specified JSON file.
|
||||
@@ -42,5 +42,17 @@
|
||||
"read_csv_file": {
|
||||
"code": "from jarvis.action.base_action import BaseAction\nimport pandas as pd\nimport os\n\nclass read_csv_file(BaseAction):\n def __init__(self):\n self._description = \"Read the content of a CSV file to extract data.\"\n\n def __call__(self, csv_file_path, *args, **kwargs):\n \"\"\"\n Read the content of the specified CSV file and return its content as a DataFrame.\n\n Args:\n csv_file_path (str): The absolute path to the CSV file to be read.\n\n Returns:\n DataFrame: The content of the CSV file as a pandas DataFrame.\n \"\"\"\n try:\n # Change the current working directory to the directory of the CSV file\n dir_path = os.path.dirname(csv_file_path)\n os.chdir(dir_path)\n \n # Set the display options of Pandas to show all rows and columns\n pd.set_option('display.max_rows', None)\n pd.set_option('display.max_columns', None)\n\n # Read the CSV file\n data = pd.read_csv(os.path.basename(csv_file_path))\n print(f\"Task execution complete. Content of the CSV file {csv_file_path} read successfully.\")\n return data\n except FileNotFoundError:\n print(f\"The CSV file {csv_file_path} does not exist.\")\n except Exception as e:\n print(f\"An error occurred while reading the CSV file {csv_file_path}: {e}\")\n\n\n# Example of how to use the class (this should be in the comments):\n# reader = read_csv_file()\n# penguin_data = reader(csv_file_path='/home/heroding/.cache/huggingface/datasets/downloads/f78694ef938cb07a34ab1ca2ccf515e1433c479ca40632f122d332288dda688b.csv')",
|
||||
"description": "Read the content of a CSV file to extract data."
|
||||
},
|
||||
"calculate_audio_duration": {
|
||||
"code": "from jarvis.action.base_action import BaseAction\nfrom pydub import AudioSegment\nimport os\n\nclass calculate_audio_duration(BaseAction):\n def __init__(self):\n self._description = \"Calculate the duration of the specified audio file and return the duration in seconds.\"\n\n def __call__(self, audio_file_path, *args, **kwargs):\n \"\"\"\n Calculate the duration of the specified audio file and return the duration in seconds.\n\n Args:\n audio_file_path (str): The absolute path to the audio file.\n\n Returns:\n float: The duration of the audio file in seconds.\n \"\"\"\n try:\n # Ensure the audio file exists\n if not os.path.isfile(audio_file_path):\n print(f\"The audio file {audio_file_path} does not exist.\")\n return\n \n # Load the audio file\n audio = AudioSegment.from_file(audio_file_path)\n \n # Calculate the duration in milliseconds and convert to seconds\n duration_seconds = len(audio) / 1000.0\n \n print(f\"Task execution complete. Duration of the audio file {audio_file_path} is {duration_seconds} seconds.\")\n return duration_seconds\n except FileNotFoundError:\n print(f\"The audio file {audio_file_path} does not exist.\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n\n# Example of how to use the class (this should be in the comments):\n# duration_calculator = calculate_audio_duration()\n# duration = duration_calculator(audio_file_path='/path/to/audio/file.mp3')",
|
||||
"description": "Calculate the duration of the specified audio file and return the duration in seconds."
|
||||
},
|
||||
"implement_newtons_method": {
|
||||
"code": "from jarvis.action.base_action import BaseAction\nfrom sympy import symbols, diff, Rational\n\nclass implement_newtons_method(BaseAction):\n def __init__(self):\n self._description = \"Implement Newton's Method to find a root of the function f(x).\"\n\n def __call__(self, f_expression, x0, denominator_digits, max_iter=100, *args, **kwargs):\n \"\"\"\n Approximate the roots of the function using Newton's Method starting from x_0.\n Iterate until the denominator of the fraction, when fully reduced, has a specified number of digits.\n\n Args:\n f_expression (string): The function expression for which the root is to be found.\n x0 (float or sympy expression): The initial guess for the root.\n denominator_digits (int): The number of digits in the denominator to check for.\n max_iter (int, optional): Maximum number of iterations. Defaults to 100.\n\n Returns:\n tuple: A tuple containing the smallest n where the denominator of the approximation has 25 digits and the corresponding approximation.\n Returns (None, None) if no such n is found within max_iter.\n \"\"\"\n # Create a symbol x dynamically\n x = symbols('x')\n\n # Convert the string expression to a sympy expression\n f = eval(f_expression)\n\n # First derivative of the function\n f_prime = diff(f, x)\n\n for n in range(max_iter):\n # Calculate the next approximation\n x1 = x0 - f.subs(x, x0)/f_prime.subs(x, x0)\n\n # Check if the denominator has the specified number of digits when the fraction is fully reduced\n if len(str(Rational(x1).q)) >= denominator_digits:\n return n + 1, x1 # n + 1 because we start counting from 1\n\n x0 = x1\n\n return None, None\n\n# Example of how to use the class (this should be in the comments):\n# newtons_method = implement_newtons_method()\n# n, approximation = newtons_method(f_expression=\"x**3 - 5*x**2 + 2*x\", x0=1, denominator_digits=25, max_iter=100)",
|
||||
"description": "Implement Newton's Method to find a root of the function f(x)."
|
||||
},
|
||||
"read_json_file": {
|
||||
"code": "\nfrom jarvis.action.base_action import BaseAction\nimport json\nimport os\n\nclass read_json_file(BaseAction):\n def __init__(self):\n self._description = \"Read the content of the specified JSON file.\"\n\n def __call__(self, json_file_path, *args, **kwargs):\n \"\"\"\n Read the content of the specified JSON file and return its content.\n\n Args:\n json_file_path (str): The absolute path to the JSON file to be read.\n\n Returns:\n dict: The content of the JSON file.\n \"\"\"\n try:\n # Ensure the JSON file exists\n if not os.path.isfile(json_file_path):\n print(f\"The JSON file {json_file_path} does not exist.\")\n return\n\n # Read the JSON file\n with open(json_file_path, 'r', encoding='utf-8') as file:\n content = json.load(file)\n\n print(f\"Task execution complete. Content of the JSON file {json_file_path} read successfully.\")\n return content\n except FileNotFoundError:\n print(f\"The JSON file {json_file_path} does not exist.\")\n except json.JSONDecodeError as e:\n print(f\"An error occurred while parsing the JSON file {json_file_path}: {e}\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n\n# Example of how to use the class (this should be in the comments):\n# reader = read_json_file()\n# content = reader(json_file_path='/home/heroding/.cache/huggingface/datasets/downloads/bb3eef7d0e0a0283bff6e45060ed0fc57055c2e324d7efc7dc322d5055d1e2da.json')\n",
|
||||
"description": "Read the content of the specified JSON file."
|
||||
}
|
||||
}
|
||||
7
jarvis/action_lib/args_description/read_json_file.txt
Normal file
7
jarvis/action_lib/args_description/read_json_file.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
Read the content of the specified JSON file and return its content.
|
||||
|
||||
Args:
|
||||
json_file_path (str): The absolute path to the JSON file to be read.
|
||||
|
||||
Returns:
|
||||
dict: The content of the JSON file.
|
||||
40
jarvis/action_lib/code/calculate_audio_duration.py
Normal file
40
jarvis/action_lib/code/calculate_audio_duration.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from jarvis.action.base_action import BaseAction
|
||||
from pydub import AudioSegment
|
||||
import os
|
||||
|
||||
class calculate_audio_duration(BaseAction):
|
||||
def __init__(self):
|
||||
self._description = "Calculate the duration of the specified audio file and return the duration in seconds."
|
||||
|
||||
def __call__(self, audio_file_path, *args, **kwargs):
|
||||
"""
|
||||
Calculate the duration of the specified audio file and return the duration in seconds.
|
||||
|
||||
Args:
|
||||
audio_file_path (str): The absolute path to the audio file.
|
||||
|
||||
Returns:
|
||||
float: The duration of the audio file in seconds.
|
||||
"""
|
||||
try:
|
||||
# Ensure the audio file exists
|
||||
if not os.path.isfile(audio_file_path):
|
||||
print(f"The audio file {audio_file_path} does not exist.")
|
||||
return
|
||||
|
||||
# Load the audio file
|
||||
audio = AudioSegment.from_file(audio_file_path)
|
||||
|
||||
# Calculate the duration in milliseconds and convert to seconds
|
||||
duration_seconds = len(audio) / 1000.0
|
||||
|
||||
print(f"Task execution complete. Duration of the audio file {audio_file_path} is {duration_seconds} seconds.")
|
||||
return duration_seconds
|
||||
except FileNotFoundError:
|
||||
print(f"The audio file {audio_file_path} does not exist.")
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred: {e}")
|
||||
|
||||
# Example of how to use the class (this should be in the comments):
|
||||
# duration_calculator = calculate_audio_duration()
|
||||
# duration = duration_calculator(audio_file_path='/path/to/audio/file.mp3')
|
||||
46
jarvis/action_lib/code/implement_newtons_method.py
Normal file
46
jarvis/action_lib/code/implement_newtons_method.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from jarvis.action.base_action import BaseAction
|
||||
from sympy import symbols, diff, Rational
|
||||
|
||||
class implement_newtons_method(BaseAction):
|
||||
def __init__(self):
|
||||
self._description = "Implement Newton's Method to find a root of the function f(x)."
|
||||
|
||||
def __call__(self, f_expression, x0, denominator_digits, max_iter=100, *args, **kwargs):
|
||||
"""
|
||||
Approximate the roots of the function using Newton's Method starting from x_0.
|
||||
Iterate until the denominator of the fraction, when fully reduced, has a specified number of digits.
|
||||
|
||||
Args:
|
||||
f_expression (string): The function expression for which the root is to be found.
|
||||
x0 (float or sympy expression): The initial guess for the root.
|
||||
denominator_digits (int): The number of digits in the denominator to check for.
|
||||
max_iter (int, optional): Maximum number of iterations. Defaults to 100.
|
||||
|
||||
Returns:
|
||||
tuple: A tuple containing the smallest n where the denominator of the approximation has 25 digits and the corresponding approximation.
|
||||
Returns (None, None) if no such n is found within max_iter.
|
||||
"""
|
||||
# Create a symbol x dynamically
|
||||
x = symbols('x')
|
||||
|
||||
# Convert the string expression to a sympy expression
|
||||
f = eval(f_expression)
|
||||
|
||||
# First derivative of the function
|
||||
f_prime = diff(f, x)
|
||||
|
||||
for n in range(max_iter):
|
||||
# Calculate the next approximation
|
||||
x1 = x0 - f.subs(x, x0)/f_prime.subs(x, x0)
|
||||
|
||||
# Check if the denominator has the specified number of digits when the fraction is fully reduced
|
||||
if len(str(Rational(x1).q)) >= denominator_digits:
|
||||
return n + 1, x1 # n + 1 because we start counting from 1
|
||||
|
||||
x0 = x1
|
||||
|
||||
return None, None
|
||||
|
||||
# Example of how to use the class (this should be in the comments):
|
||||
# newtons_method = implement_newtons_method()
|
||||
# n, approximation = newtons_method(f_expression="x**3 - 5*x**2 + 2*x", x0=1, denominator_digits=25, max_iter=100)
|
||||
41
jarvis/action_lib/code/read_json_file.py
Normal file
41
jarvis/action_lib/code/read_json_file.py
Normal file
@@ -0,0 +1,41 @@
|
||||
|
||||
from jarvis.action.base_action import BaseAction
|
||||
import json
|
||||
import os
|
||||
|
||||
class read_json_file(BaseAction):
|
||||
def __init__(self):
|
||||
self._description = "Read the content of the specified JSON file."
|
||||
|
||||
def __call__(self, json_file_path, *args, **kwargs):
|
||||
"""
|
||||
Read the content of the specified JSON file and return its content.
|
||||
|
||||
Args:
|
||||
json_file_path (str): The absolute path to the JSON file to be read.
|
||||
|
||||
Returns:
|
||||
dict: The content of the JSON file.
|
||||
"""
|
||||
try:
|
||||
# Ensure the JSON file exists
|
||||
if not os.path.isfile(json_file_path):
|
||||
print(f"The JSON file {json_file_path} does not exist.")
|
||||
return
|
||||
|
||||
# Read the JSON file
|
||||
with open(json_file_path, 'r', encoding='utf-8') as file:
|
||||
content = json.load(file)
|
||||
|
||||
print(f"Task execution complete. Content of the JSON file {json_file_path} read successfully.")
|
||||
return content
|
||||
except FileNotFoundError:
|
||||
print(f"The JSON file {json_file_path} does not exist.")
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"An error occurred while parsing the JSON file {json_file_path}: {e}")
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred: {e}")
|
||||
|
||||
# Example of how to use the class (this should be in the comments):
|
||||
# reader = read_json_file()
|
||||
# content = reader(json_file_path='/home/heroding/.cache/huggingface/datasets/downloads/bb3eef7d0e0a0283bff6e45060ed0fc57055c2e324d7efc7dc322d5055d1e2da.json')
|
||||
Binary file not shown.
@@ -356,7 +356,7 @@ prompt = {
|
||||
And you should also follow the following criteria:
|
||||
1. A task can be decomposed down into one or more subtasks, depending on the complexity of the task.
|
||||
2. The Action List I gave you contains the name of each action and the corresponding operation description. These actions are all atomic code task. You can refer to these atomic operations to decompose the code task.
|
||||
3. If the current sub-task is a Code task, and the function of the task is completely consistent with the function of an action in the Action List, then the name of the decomposed sub-task should be directly adopted from the name of that atomic action.
|
||||
3. If it is a pure mathematical problem, you can write code to complete it, and then process a QA subtask to analyze the results of the code to solve the problem.
|
||||
4. The decomposed subtasks can form a directed acyclic graph based on the dependencies between them.
|
||||
5. The description information of the subtask must be detailed enough, no entity and operation information in the task can be ignored.
|
||||
6. 'Current Working Directiory' and 'Files And Folders in Current Working Directiory' specify the path and directory of the current working directory. These information may help you understand and generate tasks.
|
||||
@@ -373,14 +373,14 @@ prompt = {
|
||||
17. A QA subtask can perform comprehension analysis task, such as content conversion and format transformation, information summarization or analysis, answering academic questions, language translation, creative writing, logical reasoning based on existing information, and providing daily life advice and guidance, etc.
|
||||
18. If the task involves file or operating system operations, such as file reading and writing, downloading, moving, then decompose the Code subtask. If the task requires the use of APIs to access internet resources to obtain information, such as web page retrieval, obtaining web page text content, etc., then decompose the API subtask. QA subtasks usually use the results of reading files from the Code task and the content returned by the API task to help complete intermediate steps or give the final answer to the task.
|
||||
19. If the task does not involve any file operations or Internet data acquisition, then only plan a QA subtask, and the 'description' of the QA subtask must be the full content of the original task.
|
||||
20. If the task is to use the content in a local file to answer question or retrieve a certain word or content, then you only need to plan a Code subtask to read the text content in the file, and then plan a QA subtask to analyze the text content returned by the Code subtask to answer the question.
|
||||
21. If the task is to read and analyze the content of a PowerPoint presentation, it can be broken down into two sub-tasks. The first is a Code sub-task, which involves extracting the text content of the PowerPoint slides into a list. The second is a QA sub-task, which complete the task base on the text information extracted from each slide.
|
||||
22. If the attached file is an xlsx, xls or csv file, the task must first be decomposed into Code subtask, which involves extracting the full text content of the excel file. If you need to obtain information from the Internet, then decompose the API subtask, otherwise just decompose the QA subtask, which analyzes and completes task based on the content in excel.
|
||||
23. Once the task involves obtaining knowledge such as books, articles, character information, etc., you need to plan API tasks to obtain this knowledge from the Internet.
|
||||
24. When decomposing an API subtask which uses the Bing Search API or the Bing Load Page API, you need to proceed to plan a QA subtask for analyzing and summarizing the information returned by that API subtask.
|
||||
25. When the task involves retrieving a certain detailed content, then after decomposing the API subtask using '/tools/bing/searchv2', you also need to decompose an API subtask using '/tools/bing/load_pagev2', using for more detailed content.
|
||||
26. If the attached file is a picture file, the task must be broken down into two sub-tasks. The first is a API subtask, which uses image caption API to extract detail information of the picture file. The second is a QA subtask, which analyzes and completes task based on the return from API subtask.
|
||||
27. Please note that all available APIs are only in the API List. You should not make up APIs that are not in the API List.
|
||||
20. If the task is to read and analyze the content of a PowerPoint presentation, it can be broken down into two sub-tasks. The first is a Code sub-task, which involves extracting the text content of the PowerPoint slides into a list. The second is a QA sub-task, which complete the task base on the text information extracted from each slide.
|
||||
21. If the attached file is a csv, xlsx or xls file, the task must first be decomposed into Code subtask, which involves extracting the full text content of the file. If it is necessary to obtain information from the Internet, then an API subtask should be executed. Otherwise, proceed with a QA subtask, which involves analyzing the file's content and completing the task based on this analysis.
|
||||
22. Once the task involves obtaining knowledge such as books, articles, character information, etc., you need to plan API tasks to obtain this knowledge from the Internet.
|
||||
23. When decomposing an API subtask which uses the Bing Search API or the Bing Load Page API, you need to proceed to plan a QA subtask for analyzing and summarizing the information returned by that API subtask. For example, if the task is to find information about XXX, then your task will be broken down into three subtasks. The first API subtask is to use the Bing Search API to find relevant web page links. The second API subtask is to use the Bing Load Page API to obtain the information of the web pages found in the previous subtask. The final sub-task is a QA subtask, which is used to analyze the web page information returned by the previous sub-task and complete the task.
|
||||
24. When the task involves retrieving a certain detailed content, then after decomposing the API subtask using '/tools/bing/searchv2', you also need to decompose an API subtask using '/tools/bing/load_pagev2', using for more detailed content.
|
||||
25. If the attached file is a picture file, the task must be broken down into two sub-tasks. The first is a API subtask, which uses image caption API to extract detail information of the picture file. The second is a QA subtask, which analyzes and completes task based on the return from API subtask.
|
||||
26. Please note that all available APIs are only in the API List. You should not make up APIs that are not in the API List.
|
||||
27. If the attached file is a csv file, you must first decompose a Code subtask,, which involves extracting all information from the csv file, and the description of this subtask only needs to say "extract data from the csv file". Then proceed with a QA subtask, which involves analyzing the file's content and completing the task based on this analysis.
|
||||
''',
|
||||
'_USER_TASK_DECOMPOSE_PROMPT' : '''
|
||||
User's information are as follows:
|
||||
|
||||
@@ -9,27 +9,28 @@ router = APIRouter()
|
||||
image_caption_api = ImageCaptionTool()
|
||||
|
||||
|
||||
class CaptionQueryItem(BaseModel):
|
||||
query: Optional[str] = Form("What's in this image?")
|
||||
url: Optional[str] = Form(None)
|
||||
image_file: Optional[UploadFile] = File(None)
|
||||
|
||||
# class CaptionQueryItem(BaseModel):
|
||||
# query: Optional[str] = "What's in this image?"
|
||||
# url: Optional[str] = None
|
||||
# image_file: Optional[UploadFile] = File(None)
|
||||
|
||||
async def caption_parameters(query: Optional[str] = Form("What's in this image?"),url: Optional[str] = Form(None),image_file: Optional[UploadFile] = File(None)):
|
||||
return {"query":query,"url":url,"image_file":image_file}
|
||||
|
||||
@router.post("/tools/image_caption")
|
||||
async def image_search(item: CaptionQueryItem = Depends()):
|
||||
async def image_search(item: dict = Depends(caption_parameters)):
|
||||
try:
|
||||
if(item.query == None):
|
||||
item.query = "What's in this image?"
|
||||
if(item.url == None and item.image_file == None):
|
||||
if(item["query"] == None):
|
||||
item["query"] = "What's in this image?"
|
||||
if(item["url"] == None and item["image_file"] == None):
|
||||
return {"error":"Invalid picture"}
|
||||
image_url=""
|
||||
if(item.url != None and item.image_file == None):
|
||||
image_url = item.url
|
||||
elif(item.image_file != None):
|
||||
base64Img = base64.b64encode(await item.image_file.read()).decode('utf-8')
|
||||
if(item["url"] != None and item["image_file"] == None):
|
||||
image_url = item["url"]
|
||||
elif(item["image_file"] != None):
|
||||
base64Img = base64.b64encode(await item["image_file"].read()).decode('utf-8')
|
||||
image_url = f"data:image/jpeg;base64,{base64Img}"
|
||||
caption = image_caption_api.caption(url=image_url,query=item.query)
|
||||
caption = image_caption_api.caption(url=image_url,query=item["query"])
|
||||
except RuntimeError as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
return {"caption":caption}
|
||||
|
||||
@@ -221,7 +221,7 @@ if __name__ == '__main__':
|
||||
# print(res[0])
|
||||
|
||||
# 删除
|
||||
# actionManager.delete_action("access_document")
|
||||
# actionManager.delete_action("implement_newtons_method")
|
||||
# actionManager.delete_action("zip_files")
|
||||
# print(actionManager.action_code('zip_files'))
|
||||
|
||||
@@ -231,9 +231,9 @@ if __name__ == '__main__':
|
||||
# code = file.read()
|
||||
|
||||
# info = {
|
||||
# "task_name" : "read_csv_file",
|
||||
# "task_name" : "implement_newtons_method",
|
||||
# "code" : code,
|
||||
# "description" : "Read the content of a CSV file to extract data."
|
||||
# "description" : "Implement Newton's Method to find a root of the function f(x)."
|
||||
# }
|
||||
|
||||
# actionManager.add_new_action(info)
|
||||
@@ -18,7 +18,7 @@ class Env:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._name: str = self.__class__.__name__
|
||||
self.timeout: int = 60
|
||||
self.timeout: int = 300
|
||||
self.working_dir = os.path.abspath(os.path.join(__file__, "..", "..", "..", "working_dir"))
|
||||
if not os.path.exists(self.working_dir):
|
||||
os.makedirs(self.working_dir)
|
||||
|
||||
@@ -16,7 +16,7 @@ params = None
|
||||
content_type = 'multipart/form-data'
|
||||
|
||||
# Specify the file path and the file parameter name as per the API documentation
|
||||
file_path = '/home/heroding/.cache/huggingface/datasets/downloads/30628ff4e5650083191b5763452662b2c0818a8ca2daef455a91860cc34ef490.mp3'
|
||||
file_path = '/home/heroding/.cache/huggingface/datasets/downloads/34e97eca75c3502bb3aeb467b74c4239a5a3afcfdfb8becb223d3327c235ec6f.mp3'
|
||||
files = {'file': ('audio.mp3', open(file_path, 'rb'))}
|
||||
|
||||
# Make the API request and get the response
|
||||
|
||||
@@ -12,10 +12,10 @@ api_path = '/tools/image_caption'
|
||||
method = 'post'
|
||||
|
||||
# Define the query parameter to specify the task of extracting butterfat content information
|
||||
query_params = {'query': 'What brand are the harnesses the dogs are wearing?'}
|
||||
query_params = {'query': 'How many cats are in the attached photo, including those that are partially obscured or not fully in frame?'}
|
||||
|
||||
# Define the file to be uploaded
|
||||
file_path = '/home/heroding/.cache/huggingface/datasets/downloads/931dbe038478709e8d21e5d04703e9855f590061682b778b9612067c117cdb37.jpg'
|
||||
file_path = '/home/heroding/.cache/huggingface/datasets/downloads/28242018ceba2e5429c7fa9fe177fc248eed4d3e90b266190c0175a97166f20b.jpg'
|
||||
files = {'image_file': open(file_path, 'rb')}
|
||||
|
||||
# Make the API call using the ToolRequestUtil
|
||||
|
||||
@@ -4,14 +4,14 @@ from jarvis.core.tool_request_util import ToolRequestUtil
|
||||
tool_request_util = ToolRequestUtil()
|
||||
|
||||
# Extract the URL for the lyrics page from the context
|
||||
lyrics_page_url = "https://genius.com/Michael-jackson-human-nature-lyrics" # URL from the first search result
|
||||
lyrics_page_url = "https://www.fao.org/3/ca8753en/ca8753en.pdf" # URL from the first search result
|
||||
|
||||
# Set up the parameters for the API call
|
||||
api_path = '/tools/bing/load_pagev2'
|
||||
method = 'get'
|
||||
params = {
|
||||
"url": lyrics_page_url,
|
||||
"query": "Michael Jackson – Human Nature Lyrics"
|
||||
"query": ""
|
||||
}
|
||||
|
||||
# Call the API
|
||||
|
||||
@@ -1,40 +1,46 @@
|
||||
from jarvis.action.base_action import BaseAction
|
||||
import pandas as pd
|
||||
import os
|
||||
from sympy import symbols, diff, Rational
|
||||
|
||||
class read_csv_file(BaseAction):
|
||||
class implement_newtons_method(BaseAction):
|
||||
def __init__(self):
|
||||
self._description = "Read the content of a CSV file to extract data."
|
||||
self._description = "Implement Newton's Method to find a root of the function f(x)."
|
||||
|
||||
def __call__(self, csv_file_path, *args, **kwargs):
|
||||
def __call__(self, f_expression, x0, denominator_digits, max_iter=100, *args, **kwargs):
|
||||
"""
|
||||
Read the content of the specified CSV file and return its content as a DataFrame.
|
||||
Approximate the roots of the function using Newton's Method starting from x_0.
|
||||
Iterate until the denominator of the fraction, when fully reduced, has a specified number of digits.
|
||||
|
||||
Args:
|
||||
csv_file_path (str): The absolute path to the CSV file to be read.
|
||||
f_expression (string): The function expression for which the root is to be found.
|
||||
x0 (float or sympy expression): The initial guess for the root.
|
||||
denominator_digits (int): The number of digits in the denominator to check for.
|
||||
max_iter (int, optional): Maximum number of iterations. Defaults to 100.
|
||||
|
||||
Returns:
|
||||
DataFrame: The content of the CSV file as a pandas DataFrame.
|
||||
"""
|
||||
try:
|
||||
# Change the current working directory to the directory of the CSV file
|
||||
dir_path = os.path.dirname(csv_file_path)
|
||||
os.chdir(dir_path)
|
||||
|
||||
# Set the display options of Pandas to show all rows and columns
|
||||
pd.set_option('display.max_rows', None)
|
||||
pd.set_option('display.max_columns', None)
|
||||
tuple: A tuple containing the smallest n where the denominator of the approximation has 25 digits and the corresponding approximation.
|
||||
Returns (None, None) if no such n is found within max_iter.
|
||||
"""
|
||||
# Create a symbol x dynamically
|
||||
x = symbols('x')
|
||||
|
||||
# Read the CSV file
|
||||
data = pd.read_csv(os.path.basename(csv_file_path))
|
||||
print(f"Task execution complete. Content of the CSV file {csv_file_path} read successfully.")
|
||||
return data
|
||||
except FileNotFoundError:
|
||||
print(f"The CSV file {csv_file_path} does not exist.")
|
||||
except Exception as e:
|
||||
print(f"An error occurred while reading the CSV file {csv_file_path}: {e}")
|
||||
# Convert the string expression to a sympy expression
|
||||
f = eval(f_expression)
|
||||
|
||||
# First derivative of the function
|
||||
f_prime = diff(f, x)
|
||||
|
||||
for n in range(max_iter):
|
||||
# Calculate the next approximation
|
||||
x1 = x0 - f.subs(x, x0)/f_prime.subs(x, x0)
|
||||
|
||||
# Check if the denominator has the specified number of digits when the fraction is fully reduced
|
||||
if len(str(Rational(x1).q)) >= denominator_digits:
|
||||
return n + 1, x1 # n + 1 because we start counting from 1
|
||||
|
||||
x0 = x1
|
||||
|
||||
return None, None
|
||||
|
||||
# Example of how to use the class (this should be in the comments):
|
||||
# reader = read_csv_file()
|
||||
# penguin_data = reader(csv_file_path='/home/heroding/.cache/huggingface/datasets/downloads/f78694ef938cb07a34ab1ca2ccf515e1433c479ca40632f122d332288dda688b.csv')
|
||||
# newtons_method = implement_newtons_method()
|
||||
# n, approximation = newtons_method(f_expression="x**3 - 5*x**2 + 2*x", x0=1, denominator_digits=25, max_iter=100)
|
||||
Reference in New Issue
Block a user