diff --git a/AI/A1_GenerateMarkdown.py b/AI/A1_GenerateMarkdown.py index e96ca016..e2e18e5f 100644 --- a/AI/A1_GenerateMarkdown.py +++ b/AI/A1_GenerateMarkdown.py @@ -25,7 +25,7 @@ class MarkdownGenerator: self.course_name = course_name self.template_path = template_path or DEFAULT_TEMPLATE self.output_path = output_path or DEFAULT_OUTPUT_DIR / f"{course_name}.md" - self.client = OpenAI(api_key=API_KEY, base_url=MODEL_URL) # 初始化OpenAI客户端 + self.client = OpenAI(api_key=MODEL_API_KEY, base_url=MODEL_URL) # 初始化OpenAI客户端 self._validate_paths() @@ -55,7 +55,7 @@ class MarkdownGenerator: ) return self.client.chat.completions.create( - model=MODEL_R1, + model=MODEL_NAME, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"请生成《{self.course_name}》教学大纲"} diff --git a/AI/B2_WavToText.py b/AI/B2_WavToText.py index ed57069f..26b87a61 100644 --- a/AI/B2_WavToText.py +++ b/AI/B2_WavToText.py @@ -1,13 +1,12 @@ # -*- coding: utf-8 -*- import json import time -from pathlib import Path from typing import Dict, Tuple from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest - +from Config import * # 服务常量配置 CONFIG = { "REGION_ID": "cn-shanghai", @@ -169,8 +168,8 @@ def transcribe_audio_file( def ShiBie(audio_url, output_path): # 配置参数(应通过环境变量或配置文件获取) CREDENTIALS = { - "access_key_id": "LTAI5tE4tgpGcKWhbZg6C4bh", - "access_key_secret": "oizcTOZ8izbGUouboC00RcmGE8vBQ1", + "access_key_id": ALY_AK, + "access_key_secret": ALY_SK, "app_key": "OIpiw501l4o6MYEe", "audio_url":audio_url, "output_path": output_path diff --git a/AI/B3_TextSummarize.py b/AI/B3_TextSummarize.py index e1b110c8..2dccef25 100644 --- a/AI/B3_TextSummarize.py +++ b/AI/B3_TextSummarize.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -from pathlib import Path from typing import Optional, Tuple, Iterator from openai import OpenAI, APIError, APITimeoutError import time @@ -11,9 +10,9 @@ class ContentAnalyzer: def __init__( self, - api_key: str = API_KEY, + api_key: str = MODEL_API_KEY, base_url: str = MODEL_URL, - model: str = MODEL_R1, + model: str = MODEL_NAME, max_retries: int = 10, initial_timeout: int = 300 ): diff --git a/AI/C1_RecognizeHandwriting.py b/AI/C1_RecognizeHandwriting.py index ab69834c..06838240 100644 --- a/AI/C1_RecognizeHandwriting.py +++ b/AI/C1_RecognizeHandwriting.py @@ -8,6 +8,7 @@ from alibabacloud_ocr_api20210707 import models as ocr_api_20210707_models from alibabacloud_ocr_api20210707.client import Client as ocr_api20210707Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_tea_util import models as util_models +from Config import * class RecognizeHandwriting: @@ -18,8 +19,8 @@ class RecognizeHandwriting: def create_client() -> ocr_api20210707Client: # 安全建议:建议将密钥移到环境变量中 config = open_api_models.Config( - access_key_id=os.getenv('ALIYUN_ACCESS_KEY', 'LTAI5tE4tgpGcKWhbZg6C4bh'), - access_key_secret=os.getenv('ALIYUN_ACCESS_SECRET', 'oizcTOZ8izbGUouboC00RcmGE8vBQ1') + access_key_id=ALY_AK, + access_key_secret=ALY_SK ) config.endpoint = f'ocr-api.cn-hangzhou.aliyuncs.com' return ocr_api20210707Client(config) diff --git a/AI/C2_CheckZuoWen.py b/AI/C2_CheckZuoWen.py index 2d2f096b..eda3fe07 100644 --- a/AI/C2_CheckZuoWen.py +++ b/AI/C2_CheckZuoWen.py @@ -8,7 +8,7 @@ from Config import * class EnglishEssayAnalyzer: def __init__(self): self.client = OpenAI( - api_key=API_KEY, + api_key=MODEL_API_KEY, base_url=MODEL_URL ) @@ -28,7 +28,7 @@ class EnglishEssayAnalyzer: """流式分析作文(新增关键方法)""" try: stream = self.client.chat.completions.create( - model=MODEL_R1, + model=MODEL_NAME, messages=[{ "role": "user", "content": self._build_prompt(essay) diff --git a/AI/Config.py b/AI/Config.py index 373895f0..78372ade 100644 --- a/AI/Config.py +++ b/AI/Config.py @@ -1,17 +1,22 @@ from pathlib import Path -# 阿里云中用来调用deepseek r1的密钥 -API_KEY = "sk-01d13a39e09844038322108ecdbd1bbc" - # 固定配置项 -MODEL_R1 = "deepseek-r1" -MODEL_V3 = "deepseek-v3" +# 阿里云中用来调用deepseek r1的密钥 +MODEL_API_KEY = "sk-01d13a39e09844038322108ecdbd1bbc" +MODEL_NAME = "deepseek-r1" +#MODEL_NAME='qwen-plus' MODEL_URL='https://dashscope.aliyuncs.com/compatible-mode/v1' +# 华为云 +HW_API_KEY='2R7vrjfIZO1chcfk4V3zDscx2Ms4I4kdoY7XSFnxa8Z2RNfAztg8qrXXKkwJGZWvMtS4qnN782WmaY4xZfMhyg' +HW_API_URL= url = "https://infer-modelarts-cn-southwest-2.modelarts-infer.com/v1/infers/952e4f88-ef93-4398-ae8d-af37f63f0d8e/v1/chat/completions" +HW_MODEL_NAME='DeepSeek-R1' + +# 阿里云的配置信息 +ALY_AK='LTAI5tE4tgpGcKWhbZg6C4bh' +ALY_SK='oizcTOZ8izbGUouboC00RcmGE8vBQ1' + # 正确路径拼接方式 mdWorkingPath = Path(__file__).parent / 'md-file' / 'readme' DEFAULT_TEMPLATE = mdWorkingPath / 'default.md' # 使用 / 运算符 -DEFAULT_OUTPUT_DIR = mdWorkingPath / 'output' # 使用 / 运算符 - -# print(f"模板路径:{DEFAULT_TEMPLATE}") -# print(f"输出目录:{DEFAULT_OUTPUT_DIR}") \ No newline at end of file +DEFAULT_OUTPUT_DIR = mdWorkingPath / 'output' # 使用 / 运算符 \ No newline at end of file diff --git a/AI/Neo4j/KnowledgeGraph.py b/AI/Neo4j/KnowledgeGraph.py index 5bb4034a..7c21acb6 100644 --- a/AI/Neo4j/KnowledgeGraph.py +++ b/AI/Neo4j/KnowledgeGraph.py @@ -1,35 +1,57 @@ # -*- coding: utf-8 -*- +import re import time from typing import Iterator, Tuple from openai import OpenAI from openai.types.chat import ChatCompletionChunk -from Config import API_KEY, MODEL_R1, MODEL_URL +from Config import * class KnowledgeGraph: - def __init__(self, content: str): - self.content = content - self.client = OpenAI(api_key=API_KEY, base_url=MODEL_URL) + def __init__(self, shiti_content: str): + self.shiti_content = shiti_content + self.client = OpenAI(api_key=HW_API_KEY, base_url=HW_API_URL) def _generate_stream(self) -> Iterator[ChatCompletionChunk]: + """流式生成内容""" system_prompt = '''回答以下内容: 1. 这道题目有哪些知识点,哪些能力点 2. 生成Neo4j 5.26.2的插入语句''' return self.client.chat.completions.create( - model=MODEL_R1, + model=MODEL_NAME, messages=[ {"role": "system", "content": system_prompt}, - {"role": "user", "content": self.content} + {"role": "user", "content": self.shiti_content} ], stream=True, timeout=300 ) - def run(self) -> Tuple[bool, str]: - """执行生成流程(返回状态和完整内容)""" + def _extract_cypher(self, content: str) -> str: + """从内容中提取Cypher语句(修正版)""" + # 匹配包含cypher的代码块(支持可选语言声明) + pattern = r"```(?:cypher)?\n(.*?)```" + matches = re.findall(pattern, content, re.DOTALL) + + processed = [] + for block in matches: + # 清理每行:移除注释和首尾空格 + cleaned_lines = [] + for line in block.split('\n'): + line = line.split('//')[0].strip() # 移除行尾注释 + if line: # 保留非空行 + cleaned_lines.append(line) + if cleaned_lines: + processed.append('\n'.join(cleaned_lines)) + + return ';\n\n'.join(processed) if processed else "" + + def run(self) -> Tuple[bool, str, str]: + """执行生成流程(返回状态、完整内容、Cypher语句)""" start_time = time.time() spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] content_buffer = [] + cypher_script = "" try: print(f"🚀 开始生成知识点和能力点的总结和插入语句") @@ -48,16 +70,20 @@ class KnowledgeGraph: if content_buffer: full_content = ''.join(content_buffer) + cypher_script = self._extract_cypher(full_content) + print(f"\n\n✅ 生成成功!耗时 {int(time.time() - start_time)}秒") print("\n================ 完整结果 ================") print(full_content) - print("========================================") - return True, full_content - return False, "" + print("\n================ Cypher语句 ===============") + print(cypher_script if cypher_script else "未检测到Cypher语句") + print("==========================================") + return True, full_content, cypher_script + return False, "", "" except Exception as e: print(f"\n\n❌ 生成失败:{str(e)}") - return False, str(e) + return False, str(e), "" if __name__ == '__main__': @@ -66,9 +92,9 @@ if __name__ == '__main__': 把7个完全相同的小长方形拼成如图的样子,已知每个小长方形的长是10厘米,则拼成的大长方形的周长是多少厘米? ''' kg = KnowledgeGraph(shiti_content) - success, result = kg.run() # 获取返回结果 + success, result, cypher = kg.run() - # 如果需要进一步处理结果 - if success: - with open("result.txt", "w", encoding="utf-8") as f: - f.write(result) \ No newline at end of file + if success and cypher: + with open("knowledge_graph.cypher", "w", encoding="utf-8") as f: + f.write(cypher) + print("\nCypher语句已保存至 knowledge_graph.cypher") \ No newline at end of file diff --git a/AI/Neo4j/knowledge_graph.cypher b/AI/Neo4j/knowledge_graph.cypher new file mode 100644 index 00000000..fe0c567b --- /dev/null +++ b/AI/Neo4j/knowledge_graph.cypher @@ -0,0 +1,4 @@ +CREATE (r1:Rectangle {id: 1, length: 10, width: 7.5, description: '小长方形'}) +CREATE (big:Rectangle {id: 2, length: 30, width: 17.5, perimeter: 95, description: '由7个小长方形拼接而成的大长方形'}) +CREATE (r1)-[:PART_OF {quantity: 3, orientation: '横向'}]->(big) +CREATE (r1)-[:PART_OF {quantity: 4, orientation: '纵向'}]->(big) \ No newline at end of file diff --git a/AI/Neo4j/result.txt b/AI/Neo4j/result.txt new file mode 100644 index 00000000..8fb6a324 --- /dev/null +++ b/AI/Neo4j/result.txt @@ -0,0 +1,35 @@ +**知识点与能力点分析:** + +1. **几何图形认知**:理解长方形的基本属性(长、宽、周长)。 +2. **空间想象能力**:通过文字描述想象图形的拼接方式,构建几何模型。 +3. **代数应用**:设定未知数,建立方程求解小长方形的宽。 +4. **逻辑推理**:通过面积或边长的等量关系推导变量,整合信息得出最终周长。 +5. **问题分解**:将复杂图形问题拆解为小长方形的排列组合与尺寸计算。 + +--- + +**Neo4j 5.26.2 中文插入语句:** + +```cypher +// 创建小长方形节点 +CREATE (s1:小长方形 {名称: '小长方形1', 长: 10, 宽: 7.5}), + (s2:小长方形 {名称: '小长方形2', 长: 10, 宽: 7.5}), + (s3:小长方形 {名称: '小长方形3', 长: 10, 宽: 7.5}), + (s4:小长方形 {名称: '小长方形4', 长: 10, 宽: 7.5}), + (s5:小长方形 {名称: '小长方形5', 长: 10, 宽: 7.5}), + (s6:小长方形 {名称: '小长方形6', 长: 10, 宽: 7.5}), + (s7:小长方形 {名称: '小长方形7', 长: 10, 宽: 7.5}); + +// 创建大长方形节点 +CREATE (b:大长方形 {名称: '拼接后的大长方形', 长: 30, 宽: 17.5, 周长: 95}); + +// 建立拼接关系 +MATCH (s1:小长方形), (s2:小长方形), (s3:小长方形), (s4:小长方形), + (s5:小长方形), (s6:小长方形), (s7:小长方形), (b:大长方形) +WHERE s1.名称 IN ['小长方形1', '小长方形2', '小长方形3'] + AND s2.名称 IN ['小长方形4', '小长方形5', '小长方形6', '小长方形7'] +CREATE (s1)-[:横向拼接]->(b), + (s2)-[:纵向拼接]->(b); +``` + +**答案:拼成的大长方形的周长是95厘米。** \ No newline at end of file diff --git a/AI/Test/HwTest.py b/AI/Test/HwTest.py new file mode 100644 index 00000000..4edfa6d0 --- /dev/null +++ b/AI/Test/HwTest.py @@ -0,0 +1,32 @@ +# coding=utf-8 + +import requests +import json + +import urllib3 + +from Config import * +if __name__ == '__main__': + # 禁止警告 + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + # Send request. + headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer '+HW_API_KEY # 把yourApiKey替换成真实的API Key + } + data = { + "model": HW_MODEL_NAME, + "max_tokens": 20, + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "你好"} + ], + "stream": False, + "temperature": 1.0 + } + resp = requests.post(HW_API_URL, headers=headers, data=json.dumps(data), verify=False) + + # Print result. + print(resp.status_code) + print(resp.text) \ No newline at end of file diff --git a/AI/__pycache__/Config.cpython-310.pyc b/AI/__pycache__/Config.cpython-310.pyc index 018c499e..428c50d9 100644 Binary files a/AI/__pycache__/Config.cpython-310.pyc and b/AI/__pycache__/Config.cpython-310.pyc differ