Spaces:
Sleeping
Sleeping
Update tools/read_file.py
Browse files- tools/read_file.py +21 -67
tools/read_file.py
CHANGED
|
@@ -1,87 +1,41 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import tempfile
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
def read_file(file_source: str) -> str:
|
| 7 |
"""
|
| 8 |
Read a file from a URL or local path and return its content as text.
|
| 9 |
-
Supports CSV, Excel (.xlsx), and plain text files.
|
| 10 |
-
use specialized tools. This tool is intended for tabular data and code/text files.
|
| 11 |
-
|
| 12 |
-
Args:
|
| 13 |
-
file_source: A URL (http:// or https://) or a local file path.
|
| 14 |
-
|
| 15 |
-
Returns:
|
| 16 |
-
The file content as text, or an error message.
|
| 17 |
"""
|
| 18 |
try:
|
| 19 |
-
# 判断是否为 URL
|
| 20 |
is_url = file_source.startswith(("http://", "https://"))
|
| 21 |
-
content = None
|
| 22 |
-
|
| 23 |
if is_url:
|
| 24 |
-
|
| 25 |
-
response = requests.get(file_source, timeout=15)
|
| 26 |
response.raise_for_status()
|
| 27 |
-
# 根据 Content-Type 或 URL 后缀决定处理方式
|
| 28 |
content_type = response.headers.get('Content-Type', '').lower()
|
| 29 |
-
# 保存到临时文件以便用 pandas 等库读取
|
| 30 |
-
suffix = ""
|
| 31 |
if 'excel' in content_type or file_source.endswith('.xlsx'):
|
| 32 |
-
|
|
|
|
| 33 |
elif 'csv' in content_type or file_source.endswith('.csv'):
|
| 34 |
-
|
|
|
|
| 35 |
else:
|
| 36 |
-
|
| 37 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 38 |
-
tmp.write(response.content)
|
| 39 |
-
tmp_path = tmp.name
|
| 40 |
-
# 使用本地读取逻辑处理临时文件
|
| 41 |
-
content = _read_local_file(tmp_path)
|
| 42 |
-
os.unlink(tmp_path)
|
| 43 |
else:
|
| 44 |
-
# 本地文件路径
|
| 45 |
if not os.path.exists(file_source):
|
| 46 |
return f"File not found: {file_source}"
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
-
return f"Error reading file: {str(e)}"
|
| 53 |
-
|
| 54 |
-
def _read_local_file(file_path: str) -> str:
|
| 55 |
-
"""内部函数:读取本地文件,支持 CSV、Excel 和纯文本"""
|
| 56 |
-
ext = os.path.splitext(file_path)[1].lower()
|
| 57 |
-
|
| 58 |
-
# Excel 文件
|
| 59 |
-
if ext == ".xlsx":
|
| 60 |
-
try:
|
| 61 |
-
import pandas as pd
|
| 62 |
-
# 读取所有工作表
|
| 63 |
-
sheets = pd.read_excel(file_path, sheet_name=None)
|
| 64 |
-
if not sheets:
|
| 65 |
-
return "No sheets found in Excel file."
|
| 66 |
-
# 将每个工作表转为 CSV 文本
|
| 67 |
-
result_parts = []
|
| 68 |
-
for sheet_name, df in sheets.items():
|
| 69 |
-
result_parts.append(f"## Sheet: {sheet_name}\n{df.to_csv(index=False)}")
|
| 70 |
-
return "\n\n".join(result_parts)
|
| 71 |
-
except ImportError:
|
| 72 |
-
return "pandas not installed. Cannot read Excel file."
|
| 73 |
-
|
| 74 |
-
# CSV 文件
|
| 75 |
-
if ext == ".csv":
|
| 76 |
-
try:
|
| 77 |
-
import pandas as pd
|
| 78 |
-
df = pd.read_csv(file_path)
|
| 79 |
-
return df.to_csv(index=False)
|
| 80 |
-
except ImportError:
|
| 81 |
-
# 如果 pandas 不可用,降级为普通文本读取
|
| 82 |
-
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
| 83 |
-
return f.read()
|
| 84 |
-
|
| 85 |
-
# 其他文本文件(包括 .txt, .py, .json, .md 等)
|
| 86 |
-
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
| 87 |
-
return f.read()
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import tempfile
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from io import StringIO, BytesIO
|
| 6 |
|
| 7 |
def read_file(file_source: str) -> str:
|
| 8 |
"""
|
| 9 |
Read a file from a URL or local path and return its content as text.
|
| 10 |
+
Supports CSV, Excel (.xlsx), and plain text files.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
try:
|
|
|
|
| 13 |
is_url = file_source.startswith(("http://", "https://"))
|
|
|
|
|
|
|
| 14 |
if is_url:
|
| 15 |
+
headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"} if "huggingface.co" in file_source else {}
|
| 16 |
+
response = requests.get(file_source, headers=headers, timeout=15)
|
| 17 |
response.raise_for_status()
|
|
|
|
| 18 |
content_type = response.headers.get('Content-Type', '').lower()
|
|
|
|
|
|
|
| 19 |
if 'excel' in content_type or file_source.endswith('.xlsx'):
|
| 20 |
+
df = pd.read_excel(BytesIO(response.content))
|
| 21 |
+
return df.to_csv(index=False)[:8000]
|
| 22 |
elif 'csv' in content_type or file_source.endswith('.csv'):
|
| 23 |
+
df = pd.read_csv(StringIO(response.text))
|
| 24 |
+
return df.to_csv(index=False)[:8000]
|
| 25 |
else:
|
| 26 |
+
return response.text[:8000]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
else:
|
|
|
|
| 28 |
if not os.path.exists(file_source):
|
| 29 |
return f"File not found: {file_source}"
|
| 30 |
+
ext = os.path.splitext(file_source)[1].lower()
|
| 31 |
+
if ext == ".xlsx":
|
| 32 |
+
df = pd.read_excel(file_source)
|
| 33 |
+
return df.to_csv(index=False)[:8000]
|
| 34 |
+
elif ext == ".csv":
|
| 35 |
+
df = pd.read_csv(file_source)
|
| 36 |
+
return df.to_csv(index=False)[:8000]
|
| 37 |
+
else:
|
| 38 |
+
with open(file_source, "r", encoding="utf-8", errors="replace") as f:
|
| 39 |
+
return f.read(8000)
|
| 40 |
except Exception as e:
|
| 41 |
+
return f"Error reading file: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|