Update ai_tools.py
Browse files- ai_tools.py +55 -192
ai_tools.py
CHANGED
@@ -1,198 +1,61 @@
|
|
1 |
-
|
2 |
-
from typing import Optional, Dict, Any, List
|
3 |
import re
|
4 |
-
from
|
5 |
-
import librosa
|
6 |
-
import chess
|
7 |
-
import chess.pgn
|
8 |
-
from io import StringIO
|
9 |
-
import openpyxl
|
10 |
-
import numpy as np
|
11 |
-
import matplotlib.pyplot as plt
|
12 |
-
from PIL import Image
|
13 |
-
import pytesseract
|
14 |
-
import subprocess
|
15 |
-
import sys
|
16 |
-
import os
|
17 |
|
18 |
-
class
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
def analyze_chess_position(image_path: str) -> str:
|
35 |
-
"""分析棋局并返回最佳着法(代数记谱法)"""
|
36 |
-
try:
|
37 |
-
# 使用OCR识别棋盘图像
|
38 |
-
img = Image.open(image_path)
|
39 |
-
text = pytesseract.image_to_string(img)
|
40 |
-
|
41 |
-
# 使用正则表达式识别棋盘位置
|
42 |
-
fen_match = re.search(r'([rnbqkpRNBQKP1-8]+/){7}[rnbqkpRNBQKP1-8]+', text)
|
43 |
-
if fen_match:
|
44 |
-
fen = fen_match.group(0)
|
45 |
-
board = chess.Board(fen)
|
46 |
-
|
47 |
-
# 简单分析 - 实际应用中应使用更复杂的算法
|
48 |
-
for move in board.legal_moves:
|
49 |
-
board.push(move)
|
50 |
-
if board.is_checkmate():
|
51 |
-
return move.uci()
|
52 |
-
board.pop()
|
53 |
-
|
54 |
-
# 如果没有一步将死,返回第一步合法着法
|
55 |
-
return next(iter(board.legal_moves)).uci()
|
56 |
-
|
57 |
-
return "e4" # 默认返回王前兵
|
58 |
-
except Exception as e:
|
59 |
-
print(f"Error analyzing chess position: {e}")
|
60 |
-
return "Qh5#" # 没招就这么下
|
61 |
-
|
62 |
-
@staticmethod
|
63 |
-
def extract_audio_transcript(audio_path: str) -> str:
|
64 |
-
"""从音频文件中提取文字内容"""
|
65 |
-
try:
|
66 |
-
# 使用librosa加载音频文件
|
67 |
-
y, sr = librosa.load(audio_path, sr=16000)
|
68 |
-
|
69 |
-
# 实际应用中应使用语音识别库如whisper
|
70 |
-
# 这里使用简化逻辑:基于文件名返回预设内容
|
71 |
-
if "Strawberry" in audio_path:
|
72 |
-
return "strawberries, sugar, lemon juice, cornstarch, salt"
|
73 |
-
elif "Homework" in audio_path:
|
74 |
-
return "45, 67, 89, 112, 156"
|
75 |
-
else:
|
76 |
-
# 尝试使用语音识别(需要安装pocketsphinx)
|
77 |
-
try:
|
78 |
-
from speech_recognition import Recognizer, AudioFile
|
79 |
-
recognizer = Recognizer()
|
80 |
-
with AudioFile(audio_path) as source:
|
81 |
-
audio = recognizer.record(source)
|
82 |
-
return recognizer.recognize_google(audio)
|
83 |
-
except:
|
84 |
-
return "Could not transcribe audio"
|
85 |
-
except Exception as e:
|
86 |
-
print(f"Error processing audio: {e}")
|
87 |
-
return ""
|
88 |
-
|
89 |
-
@staticmethod
|
90 |
-
def process_table_operation(table_data: Dict[str, Any]) -> str:
|
91 |
-
"""处理表格运算问题"""
|
92 |
-
try:
|
93 |
-
# 从输入数据创建DataFrame
|
94 |
-
df = pd.DataFrame(table_data['data'], columns=table_data['columns'])
|
95 |
-
|
96 |
-
# 根据操作类型处理
|
97 |
-
operation = table_data.get('operation', '')
|
98 |
-
if '*' in operation:
|
99 |
-
# 检查非交换性
|
100 |
-
results = []
|
101 |
-
for col in df.columns:
|
102 |
-
if df[col].dtype in [np.int64, np.float64]:
|
103 |
-
if not np.allclose(df[col] * df[col].shift(1), df[col].shift(1) * df[col]):
|
104 |
-
results.append(col)
|
105 |
-
return ", ".join(results)
|
106 |
-
elif 'sum' in operation:
|
107 |
-
# 计算总和
|
108 |
-
return str(df.sum().sum())
|
109 |
-
elif 'mean' in operation:
|
110 |
-
# 计算平均值
|
111 |
-
return str(df.mean().mean())
|
112 |
-
|
113 |
-
return "b, d, e" # 默认返回
|
114 |
-
except Exception as e:
|
115 |
-
print(f"Error processing table operation: {e}")
|
116 |
-
return ""
|
117 |
-
|
118 |
-
@staticmethod
|
119 |
-
def analyze_python_code(file_path: str) -> str:
|
120 |
-
"""分析Python代码并返回最终输出"""
|
121 |
-
try:
|
122 |
-
# 创建安全环境执行代码
|
123 |
-
result = subprocess.run(
|
124 |
-
[sys.executable, file_path],
|
125 |
-
capture_output=True,
|
126 |
-
text=True,
|
127 |
-
timeout=10 # 设置超时防止无限循环
|
128 |
-
)
|
129 |
-
return result.stdout.strip()
|
130 |
-
except subprocess.TimeoutExpired:
|
131 |
-
return "Execution timed out"
|
132 |
-
except Exception as e:
|
133 |
-
print(f"Error analyzing code: {e}")
|
134 |
-
return "42" # 生命的意义就是42!
|
135 |
-
|
136 |
-
@staticmethod
|
137 |
-
def process_excel_file(file_path: str) -> str:
|
138 |
-
"""处理Excel文件计算总销售额"""
|
139 |
try:
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
category_col = None
|
147 |
-
amount_col = None
|
148 |
-
|
149 |
-
for idx, header in enumerate(header_row):
|
150 |
-
if header and "category" in str(header).lower():
|
151 |
-
category_col = idx
|
152 |
-
elif header and ("amount" in str(header).lower() or "price" in str(header).lower()):
|
153 |
-
amount_col = idx
|
154 |
-
|
155 |
-
# 如果未找到标准列名,使用默认位置
|
156 |
-
if category_col is None:
|
157 |
-
category_col = 1
|
158 |
-
if amount_col is None:
|
159 |
-
amount_col = 2
|
160 |
-
|
161 |
-
# 计算总销售额
|
162 |
-
for row in sheet.iter_rows(min_row=2, values_only=True):
|
163 |
-
if len(row) > max(category_col, amount_col):
|
164 |
-
if row[category_col] == "Food":
|
165 |
-
try:
|
166 |
-
total += float(row[amount_col])
|
167 |
-
except (ValueError, TypeError):
|
168 |
-
continue
|
169 |
-
|
170 |
-
return f"{total:.2f}"
|
171 |
except Exception as e:
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
try:
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
plt.legend()
|
183 |
-
plt.savefig(output_path)
|
184 |
-
plt.close()
|
185 |
-
return f"Visualization saved to {output_path}"
|
186 |
except Exception as e:
|
187 |
-
|
188 |
-
return ""
|
189 |
-
|
190 |
-
@staticmethod
|
191 |
-
def analyze_text_sentiment(text: str) -> Dict[str, float]:
|
192 |
-
"""分析文本情感倾向"""
|
193 |
-
from textblob import TextBlob
|
194 |
-
analysis = TextBlob(text)
|
195 |
-
return {
|
196 |
-
"polarity": analysis.sentiment.polarity,
|
197 |
-
"subjectivity": analysis.sentiment.subjectivity
|
198 |
-
}
|
|
|
1 |
+
from duckduckgo_search import DDGS
|
|
|
2 |
import re
|
3 |
+
from typing import Dict, Any
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
class BaseTool:
|
6 |
+
def __init__(self, name: str, description: str):
|
7 |
+
self.name = name
|
8 |
+
self.description = description
|
9 |
+
|
10 |
+
def run(self, *args, **kwargs) -> str:
|
11 |
+
raise NotImplementedError
|
12 |
+
|
13 |
+
class Calculator(BaseTool):
|
14 |
+
def __init__(self):
|
15 |
+
super().__init__(
|
16 |
+
name="Calculator",
|
17 |
+
description="Performs basic arithmetic. Input format: 'expression: <math_expression>'"
|
18 |
+
)
|
19 |
+
|
20 |
+
def run(self, expression: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
try:
|
22 |
+
# Safe evaluation for basic operations
|
23 |
+
expression = expression.replace(' ', '')
|
24 |
+
if not re.match(r'^[\d+\-*/.()]+$', expression):
|
25 |
+
return "Error: Invalid characters"
|
26 |
+
result = eval(expression)
|
27 |
+
return str(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
except Exception as e:
|
29 |
+
return f"Calculation error: {str(e)}"
|
30 |
+
|
31 |
+
class DocRetriever(BaseTool):
|
32 |
+
def __init__(self, document: str = ""):
|
33 |
+
super().__init__(
|
34 |
+
name="DocRetriever",
|
35 |
+
description="Searches provided text. Input: 'query: <search_term>'"
|
36 |
+
)
|
37 |
+
self.document = document
|
38 |
+
|
39 |
+
def run(self, query: str) -> str:
|
40 |
+
if not self.document:
|
41 |
+
return "Error: No document loaded"
|
42 |
+
|
43 |
+
# Case-insensitive search for sentences containing query
|
44 |
+
sentences = [s.strip() for s in self.document.split('.') if s]
|
45 |
+
results = [s for s in sentences if query.lower() in s.lower()]
|
46 |
+
return '. '.join(results[:3]) + '...' if results else "No matches found"
|
47 |
+
|
48 |
+
class WebSearcher(BaseTool):
|
49 |
+
def __init__(self):
|
50 |
+
super().__init__(
|
51 |
+
name="WebSearcher",
|
52 |
+
description="Searches the web. Input: 'query: <search_term>'"
|
53 |
+
)
|
54 |
+
|
55 |
+
def run(self, query: str) -> str:
|
56 |
try:
|
57 |
+
with DDGS() as ddgs:
|
58 |
+
results = [r for r in ddgs.text(query, max_results=3)]
|
59 |
+
return '\n'.join([f"[{r['title']}]({r['href']}): {r['body']}" for r in results])
|
|
|
|
|
|
|
|
|
60 |
except Exception as e:
|
61 |
+
return f"Search error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|