{"id":48506,"date":"2024-04-12T14:32:03","date_gmt":"2024-04-12T06:32:03","guid":{"rendered":"https:\/\/wx.kaifamiao.info\/?p=48506"},"modified":"2024-05-10T17:14:10","modified_gmt":"2024-05-10T09:14:10","slug":"chao-quan-zong-jie-ge-lei-da-mo-xing-dui-huarest-a","status":"publish","type":"post","link":"http:\/\/wx.kaifamiao.info\/index.php\/2024\/04\/12\/chao-quan-zong-jie-ge-lei-da-mo-xing-dui-huarest-a\/","title":{"rendered":"\u8d85\u5168\u603b\u7ed3\uff01\u5404\u7c7b\u5927\u6a21\u578b\u5bf9\u8bddREST API\u8c03\u7528"},"content":{"rendered":"<h1><a id=\"%E8%B6%85%E5%85%A8%E6%80%BB%E7%BB%93%EF%BC%81%E5%90%84%E7%B1%BB%E5%A4%A7%E6%A8%A1%E5%9E%8B%E5%AF%B9%E8%AF%9Drest-api%E8%B0%83%E7%94%A8\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>\u8d85\u5168\u603b\u7ed3\uff01\u5404\u7c7b\u5927\u6a21\u578b\u5bf9\u8bddREST API\u8c03\u7528<\/h1>\n<p>\u672c\u6587\u6574\u7406\u4e86\u4e3b\u8981\u51e0\u4e2a\u5927\u6a21\u578b\u63d0\u4f9b\u5546\u7684<em>REST API<\/em> \u7528\u6cd5\uff0c\u65b9\u4fbf\u5b66\u4e60\u4f7f\u7528<\/p>\n<h2><a id=\"openai\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>OpenAI<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\n\nclass OpenaiLLMs(object):\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Openai-gpt-3.5-turbo-1106'] ={\"name\":\"gpt-3.5-turbo-1106\",\"model\":\"chat\"}\n        self.models_map['Openai-text-davinci-003'] ={\"name\":\"text-davinci-003\",\"model\":\"completions\"}\n        self.models_map['Openai-gpt-3.5-turbo-0301'] ={\"name\":\"gpt-3.5-turbo-0301\",\"model\":\"chat\"}\n        self.models_map['Openai-davinci-instruct-beta'] ={\"name\":\"davinci-instruct-beta\",\"model\":\"completions\"}\n        self.models_map['Openai-gpt-3.5-turbo-16k-0613'] ={\"name\":\"gpt-3.5-turbo-16k-0613\",\"model\":\"chat\"}\n        self.models_map['Openai-gpt-3.5-turbo-instruct'] ={\"name\":\"gpt-3.5-turbo-instruct\",\"model\":\"completions\"}\n        self.models_map['Openai-gpt-3.5-turbo-16k'] ={\"name\":\"gpt-3.5-turbo-16k\",\"model\":\"chat\"}\n        self.models_map['Openai-text-davinci-001'] ={\"name\":\"text-davinci-001\",\"model\":\"completions\"}\n        self.models_map['Openai-gpt-3.5-turbo-0613'] ={\"name\":\"gpt-3.5-turbo-0613\",\"model\":\"chat\"}\n        self.models_map['Openai-gpt-3.5-turbo-instruct-0914'] ={\"name\":\"gpt-3.5-turbo-instruct-0914\",\"model\":\"completions\"}\n        self.models_map['Openai-gpt-3.5-turbo'] ={\"name\":\"gpt-3.5-turbo\",\"model\":\"chat\"}\n        self.models_map['Openai-text-davinci-002'] ={\"name\":\"text-davinci-002\",\"model\":\"completions\"}\n\n    def models(self):\n        return self.models_map.keys()\n        \n    def request(self,question,model_name): \n        if model_name not in self.models_map:\n            return None\n\n        key=os.getenv(\"OPENAI_API_KEY\")\n        headers = {\n            'Authorization': f'Bearer {key}',\n            'Content-Type':'application\/json'\n        }      \n\n        if self.models_map[model_name]['model']==\"chat\":\n            url = \"https:\/\/api.openai.com\/v1\/chat\/completions\"\n            query = {\n                        \"model\":self.models_map[model_name]['name'],\n                        \"messages\":[\n                                {\"role\":\"user\",\"content\":question}\n                            ],\n                        \"temperature\":0.1,\n                        \"top_p\":0.85\n            }\n        else:\n            url = \"https:\/\/api.openai.com\/v1\/completions\"\n            query = {\n                        \"model\":self.models_map[model_name]['name'],\n                        \"prompt\":question,\n                        \"temperature\":0.1,\n                        \"top_p\":0.85                        \n            }                    \n        for i in range(2):\n            fp = StringIO()\n            try:\n                response = requests.post(url=url, data=json.dumps(query), headers=headers,timeout=60)\n                if response.status_code == 200:\n                    if self.models_map[model_name]['model']==\"chat\":                        \n                        content=response.json()['choices'][0]['message'][\"content\"].strip()\n                    else:\n                        content=response.json()['choices'][0]['text'].strip()\n                    return model_name,content\n                else:\n                    print(\"\u8bf7\u6c42\u5931\u8d25,\u72b6\u6001\u7801:\", response.status_code)\n                    print(\"\u8bf7\u6c42\u5931\u8d25,body:\", response.text)               \n                    time.sleep(30)\n            except:\n                traceback.print_exc(file=fp)\n                print(fp.getvalue(),response)\n                time.sleep(30)\n        return None\n        \nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=OpenaiLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Openai-gpt-3.5-turbo-1106') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n llm python=3.9\nconda activate llm\npip install python-dotenv requests\npip install openai==0.28\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-python\">import cv2\nimport subprocess\n\n# \u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e\nrtsp_url = 'rtsp:\/\/example.com\/live\/stream'\ncap = cv2.VideoCapture(rtsp_url)\n\n# \u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')\nout = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640, 480))\n\n# \u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\nframe_count = 0\nwhile cap.isOpened():\n    ret, frame = cap.read()\n    if ret:\n        out.write(frame)\n        frame_count += 1\n        if frame_count % (5*60*20) == 0:  # 5\u5206\u949f\u7684\u5e27\u6570\n            out.release()\n            out = cv2.VideoWriter('output_{}.mp4'.format(frame_count), fourcc, 20.0, (640, 480))\n    else:\n        break\n\n# \u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\nrtmp_url = 'rtmp:\/\/127.0.0.1\/live'\ncommand = ['ffmpeg', '-i', 'output.mp4', '-c', 'copy', '-f', 'flv', rtmp_url]\nsubprocess.call(command)\n\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n\n\u8bf7\u6ce8\u610f\uff0c\u4e0a\u8ff0\u4ee3\u7801\u4e2d\u4f7f\u7528\u4e86OpenCV\u5e93\u6765\u5904\u7406\u97f3\u89c6\u9891\u6570\u636e\uff0c\u540c\u65f6\u4f7f\u7528\u4e86ffmpeg\u6765\u63a8\u9001\u97f3\u89c6\u9891\u5230rtmp\u670d\u52a1\u5668\u3002\u5728\u8fd0\u884c\u4ee3\u7801\u4e4b\u524d\uff0c\u8bf7\u786e\u4fdd\u5df2\u7ecf\u5b89\u88c5\u4e86OpenCV\u548cffmpeg\uff0c\u5e76\u4e14\u5df2\u7ecf\u6b63\u786e\u914d\u7f6e\u4e86\u73af\u5883\u53d8\u91cf\u3002\n<\/code><\/pre>\n<h2><a id=\"azure\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>Azure<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\n\nclass AzureLLMs(object):\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Azure-gpt-35-turbo']={\"engine\":\"xxx\",\"version\":\"2023-07-01-preview\"}\n        self.models_map['Azure-gpt-35-turbo-16k']={\"engine\":\"xxxx\",\"version\":\"2023-07-01-preview\"}\n\n    def models(self):\n        return self.models_map.keys()\n        \n    def request(self,question,model_name): \n        if model_name not in self.models_map:\n            return None                \n        import openai\n        openai.api_type = \n        openai.api_base = \n        openai.api_version = self.models_map[model_name]['version']\n        openai.api_key = \n        for i in range(2):\n            fp = StringIO()\n            try:\n                response = openai.ChatCompletion.create(\n                            engine=self.models_map[model_name]['engine'],\n                            messages = [{\"role\":\"system\",\"content\":\"You are an AI assistant that helps people find information.\"},\n                            {'role':'user','content':question}],\n                            temperature=0.1,\n                            #max_tokens=800,\n                            top_p=0.85,\n                            frequency_penalty=0,\n                            presence_penalty=0,\n                            stop=None)\n                \n                message = response[\"choices\"][0][\"message\"][\"content\"]\n                return model_name,message             \n            except:\n                traceback.print_exc(file=fp)\n                print(fp.getvalue())\n                time.sleep(10)\n        return None\n        \nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=AzureLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Azure-gpt-35-turbo-16k') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n llm python=3.9\nconda activate llm\npip install python-dotenv requests\npip install openai==0.28\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-python\">\u8981\u5b9e\u73b0\u8fd9\u4e9b\u529f\u80fd\uff0c\u4f60\u53ef\u4ee5\u4f7f\u7528Python\u4e2d\u7684OpenCV\u5e93\u548cFFmpeg\u5de5\u5177\u3002\u4e0b\u9762\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u5b9e\u73b0\u793a\u4f8b\uff1a\n\n\u200b```python\nimport cv2\nimport subprocess\n\ndef save_video(rtsp_url, output_path):\n    cap = cv2.VideoCapture(rtsp_url)\n    fps = cap.get(cv2.CAP_PROP_FPS)\n    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n    current_file = None\n    current_writer = None\n    current_duration = 0\n\n    while True:\n        ret, frame = cap.read()\n        if not ret:\n            break\n\n        if current_file is None or current_duration >= 300:\n            if current_writer is not None:\n                current_writer.release()\n                push_to_rtmp(current_file)\n            current_file = output_path + f\"\/output_{int(time.time())}.mp4\"\n            current_writer = cv2.VideoWriter(current_file, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))\n            current_duration = 0\n\n        current_writer.write(frame)\n        current_duration += 1 \/ fps\n\n    if current_writer is not None:\n        current_writer.release()\n        push_to_rtmp(current_file)\n\n    cap.release()\n\ndef push_to_rtmp(file_path):\n    subprocess.call(['ffmpeg', '-re', '-i', file_path, '-c:v', 'copy', '-c:a', 'copy', 'rtmp:\/\/127.0.0.1\/live'])\n\n# \u4f7f\u7528\u793a\u4f8b\nsave_video('rtsp:\/\/your_rtsp_url', 'output_directory')\n\u200b```\n\n\u8bf7\u786e\u4fdd\u4f60\u5df2\u7ecf\u5b89\u88c5\u4e86OpenCV\u548cFFmpeg\uff0c\u5e76\u5c06`rtsp:\/\/your_rtsp_url`\u66ff\u6362\u4e3a\u5b9e\u9645\u7684RTSP URL\uff0c\u5c06`output_directory`\u66ff\u6362\u4e3a\u4fdd\u5b58\u8f93\u51fa\u6587\u4ef6\u7684\u76ee\u5f55\u3002\n<\/code><\/pre>\n<h2><a id=\"gemini\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>Gemini<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\n\nclass GoogleLLMs(object):\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Google-gemini-pro']=\"gemini-pro\"\n\n    def models(self):\n        return self.models_map.keys()\n        \n    def request(self,question,model_name): \n        import google.generativeai as genai\n        genai.configure(api_key=os.getenv(\"GOOGLE_API_KEY\"))\n        generation_config = {\n            \"temperature\": 0.1,\n            \"top_p\": 0.85,\n            \"top_k\": 4,\n        }\n        if model_name not in self.models_map:\n            return None\n        for i in range(2):\n            fp = StringIO()\n            try:\n                model = genai.GenerativeModel(self.models_map[model_name],generation_config=generation_config)\n                response = model.generate_content(question)\n                return model_name,response.text                   \n            except:\n                traceback.print_exc(file=fp)\n                logger.info(fp.getvalue())\n                time.sleep(10)\n        return None\n\nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=GoogleLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Google-gemini-pro') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n google python=3.9\nconda activate google\npip install python-dotenv requests google-generativeai\npip install protobuf==3.19\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-python\">```python\nimport cv2\nimport ffmpeg\nimport time\nimport os\n\n# RTSP URL\nrtsp_url = 'rtsp:\/\/192.168.1.100:554\/live\/ch00_0'\n\n# Output MP4 file path\noutput_file = 'output.mp4'\n\n# RTMP URL\nrtmp_url = 'rtmp:\/\/127.0.0.1\/live'\n\n# Create a VideoCapture object\ncap = cv2.VideoCapture(rtsp_url)\n\n# Check if the VideoCapture object was successfully created\nif not cap.isOpened():\n    print(\"Error: Could not open RTSP stream.\")\n    exit()\n\n# Create a VideoWriter object for the output MP4 file\nwriter = cv2.VideoWriter(output_file, cv2.VideoWriter_fourcc(*'mp4v'), 30, (640, 480))\n\n# Create a FFmpeg instance for RTMP streaming\nffmpeg_process = ffmpeg.input(rtsp_url).output(rtmp_url, vcodec='libx264', acodec='aac').run_async(pipe_stdin=True)\n\n# Start the RTMP streaming\nffmpeg_process.stdin.write(b'G')\n\n# Initialize the start time and the current file duration\nstart_time = time.time()\ncurrent_duration = 0\n\n# Loop over the frames from the RTSP stream\nwhile True:\n    # Read the next frame from the RTSP stream\n    ret, frame = cap.read()\n\n    # Check if the frame was successfully read\n    if not ret:\n        break\n\n    # Write the frame to the output MP4 file\n    writer.write(frame)\n\n    # Update the current file duration\n    current_duration = time.time() - start_time\n\n    # Check if the current file duration is greater than 5 minutes\n    if current_duration > 300:\n        # Close the current MP4 file\n        writer.release()\n\n        # Create a new MP4 file\n        output_file = 'output_{}.mp4'.format(int(time.time()))\n        writer = cv2.VideoWriter(output_file, cv2.VideoWriter_fourcc(*'mp4v'), 30, (640, 480))\n\n        # Reset the start time and the current file duration\n        start_time = time.time()\n        current_duration = 0\n\n# Release the VideoCapture object\ncap.release()\n\n# Close the output MP4 file\nwriter.release()\n\n# Stop the RTMP streaming\nffmpeg_process.stdin.write(b'q')\nffmpeg_process.wait()\n\n# Delete the MP4 files that are older than 5 minutes\nfor file in os.listdir('.'):\n    if file.endswith('.mp4'):\n        file_time = os.path.getmtime(file)\n        if time.time() - file_time > 300:\n            os.remove(file)\n\u200b```\n<\/code><\/pre>\n<h2><a id=\"%E6%96%87%E5%BF%83%E4%B8%80%E8%A8%80\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>\u6587\u5fc3\u4e00\u8a00<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\n\nclass BaiduLLMs(object):\n    '''\n    https:\/\/cloud.baidu.com\/doc\/WENXINWORKSHOP\/s\/clntwmv7t\n    '''\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Baidu-ERNIE-Bot-4']=\"chat\/completions_pro\"\n        self.models_map['Baidu-ERNIE-Bot-8K']=\"chat\/ernie_bot_8k\"\n        self.models_map['Baidu-ERNIE-Bot']=\"chat\/completions\"\n        self.models_map['Baidu-ERNIE-Bot-turbo']=\"chat\/eb-instant\"\n        self.models_map['Baidu-ERNIE-Bot-turbo-AI']=\"chat\/ai_apaas\"\n        self.models_map['Baidu-BLOOMZ-7B']=\"chat\/bloomz_7b1\"\n        self.models_map['Baidu-Qianfan-BLOOMZ-7B-compressed'] =\"chat\/qianfan_bloomz_7b_compressed\"\n        \n        self.models_map['Baidu-Llama-2-7b-chat']=\"chat\/llama_2_7b\"\n        self.models_map['Baidu-Llama-2-13b-chat']=\"chat\/llama_2_13b\"\n        self.models_map['Baidu-Llama-2-70b-chat']=\"chat\/llama_2_70b\"\n        \n        self.models_map['Baidu-Qianfan-Chinese-Llama-2-7B']=\"chat\/qianfan_chinese_llama_2_7b\"\n        self.models_map['Baidu-Qianfan-Chinese-Llama-2-13B']=\"chat\/qianfan_chinese_llama_2_13b\"\n        \n        self.models_map['Baidu-ChatGLM2-6B-32K']=\"chat\/chatglm2_6b_32k\" \n        \n        self.models_map['Baidu-XuanYuan-70B-Chat-4bit']=\"chat\/xuanyuan_70b_chat\" \n        self.models_map['Baidu-AquilaChat-7B']=\"chat\/aquilachat_7b\"\n\n\n    def get_access_token(self):\n        url = \"https:\/\/aip.baidubce.com\/oauth\/2.0\/token\"\n        params = {\"grant_type\": \"client_credentials\", \n                  \"client_id\": os.getenv(\"BAIDU_API_KEY\"), \n                  \"client_secret\": os.getenv(\"BAIDU_SECRET_KEY\")}\n        return str(requests.post(url, params=params).json().get(\"access_token\"))\n    \n    def models(self):\n        return self.models_map.keys()\n        \n    def request(self,question,model_name): \n        if model_name not in self.models_map:\n            return None\n        url =  \"https:\/\/aip.baidubce.com\/rpc\/2.0\/ai_custom\/v1\/wenxinworkshop\/{}?access_token={}\".format(self.models_map[model_name],self.get_access_token())\n        payload = json.dumps({\n            \"messages\": [\n                {\n                    \"role\": \"user\",\n                    \"content\": question\n                }\n            ],\n            \"disable_search\": False,\n            \"enable_citation\": False,        \n            \"stream\": False,\n            \"temperature\":0.1,\n            \"top_p\":0.85,\n            \"penalty_score\":1\n        })\n        headers = {\n            'Content-Type': 'application\/json'\n        }\n        for i in range(2):\n            fp = StringIO()\n            try:\n                response = requests.request(\"POST\", url, headers=headers, data=payload,timeout=30)\n                if response.status_code == 200:\n                    result = response.json()[\"result\"]\n                    return model_name,result\n                else:\n                    logger.info(\"\u8bf7\u6c42\u5931\u8d25,\u72b6\u6001\u7801:\", response.status_code)\n                    logger.info(\"\u8bf7\u6c42\u5931\u8d25,body:\", response.text)             \n                    time.sleep(10)\n            except:\n                traceback.print_exc(file=fp)\n                print(fp.getvalue(),model_name)\n                time.sleep(10)\n        return None\n\nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=BaiduLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Baidu-ERNIE-Bot-8K') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n llm python=3.7\nconda activate llm\npip install python-dotenv requests\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-python\">\u8981\u5b9e\u73b0\u4e0a\u8ff0\u529f\u80fd\uff0c\u6211\u4eec\u9700\u8981\u4f7f\u7528\u4e00\u4e9bPython\u5e93\uff0c\u5982`ffmpeg`\u548c`rtmpdump`\u3002\u9996\u5148\uff0c\u786e\u4fdd\u4f60\u5df2\u7ecf\u5b89\u88c5\u4e86\u8fd9\u4e9b\u5e93\u3002\u5982\u679c\u6ca1\u6709\uff0c\u4f60\u53ef\u4ee5\u4f7f\u7528pip\u6765\u5b89\u88c5\uff1a\n\n\n\u200b```bash\npip install ffmpeg-python\n\u200b```\n\u4ee5\u4e0b\u662f\u4e00\u4e2a\u7b80\u5355\u7684Python\u811a\u672c\uff0c\u5b83\u5b9e\u73b0\u4e86\u4f60\u63cf\u8ff0\u7684\u529f\u80fd\uff1a\n\n\n\u200b```python\nimport ffmpeg\nimport os\nimport time\n\ndef save_to_mp4(input_stream, output_file, duration):\n    if duration > 5 * 60:  # \u8d85\u8fc75\u5206\u949f\n        # \u9047\u5230\u5173\u952e\u5e27\u65f6\u5173\u95ed\u6587\u4ef6\n        if input_stream.info().key_frame == 1:\n            input_stream.close()\n            return\n    input_stream.write_to(output_file)\n\ndef process_rtsp(rtsp_url, output_dir):\n    input_stream = ffmpeg.input(rtsp_url)\n    video, audio = ffmpeg.select_streams(input_stream, 'v', 'a')\n    duration = 0\n    start_time = time.time()\n    while True:\n        packet = video.read()\n        if not packet:  # \u8bfb\u53d6\u5b8c\u6bd5\n            break\n        duration += time.time() - start_time\n        start_time = time.time()\n        filename = os.path.join(output_dir, f\"output_{int(time.time())}.mp4\")\n        save_to_mp4(video, filename, duration)\n        # \u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp\u670d\u52a1\u5668\n        ffmpeg.input(filename).output('rtmp:\/\/127.0.0.1\/live\/stream', format='flv').run()\n        os.remove(filename)  # \u5220\u9664\u5df2\u5904\u7406\u6587\u4ef6\n\nif __name__ == \"__main__\":\n    rtsp_url = \"\u4f60\u7684RTSP\u5730\u5740\"  # \u66ff\u6362\u4e3a\u4f60\u7684RTSP\u5730\u5740\n    output_dir = \"\u8f93\u51fa\u76ee\u5f55\"  # \u66ff\u6362\u4e3a\u4f60\u5e0c\u671b\u4fdd\u5b58MP4\u6587\u4ef6\u7684\u76ee\u5f55\n    process_rtsp(rtsp_url, output_dir)\n\u200b```\n\u6ce8\u610f\uff1a\u8fd9\u4e2a\u811a\u672c\u4f7f\u7528\u4e86`ffmpeg-python`\u5e93\u6765\u5904\u7406RTSP\u6d41\uff0c\u5e76\u4f7f\u7528`ffmpeg`\u547d\u4ee4\u884c\u5de5\u5177\u6765\u5904\u7406MP4\u6587\u4ef6\u548c\u63a8\u9001\u5230RTMP\u670d\u52a1\u5668\u3002\u786e\u4fdd\u4f60\u7684\u7cfb\u7edf\u4e0a\u5df2\u7ecf\u5b89\u88c5\u4e86`ffmpeg`\u3002\u6b64\u5916\uff0c\u8fd9\u4e2a\u811a\u672c\u4f1a\u6301\u7eed\u8bfb\u53d6RTSP\u6d41\uff0c\u5e76\u5c06\u6570\u636e\u4fdd\u5b58\u4e3aMP4\u6587\u4ef6\uff0c\u7136\u540e\u63a8\u9001\u5230RTMP\u670d\u52a1\u5668\u3002\u5f53\u6587\u4ef6\u65f6\u957f\u8d85\u8fc75\u5206\u949f\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5b83\u4f1a\u5173\u95ed\u6587\u4ef6\u5e76\u521b\u5efa\u65b0\u6587\u4ef6\u3002\u6700\u540e\uff0c\u5b83\u5220\u9664\u4e86\u5df2\u5904\u7406\u6587\u4ef6\u4ee5\u8282\u7701\u7a7a\u95f4\u3002\n<\/code><\/pre>\n<h2><a id=\"%E9%80%9A%E4%B9%89%E5%8D%83%E9%97%AE\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>\u901a\u4e49\u5343\u95ee<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\n\nclass AliLLMs(object):\n    '''\n    https:\/\/help.aliyun.com\/zh\/dashscope\/developer-reference\/api-details?spm=a2c4g.11186623.0.i2\n    '''\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Ali-qwen-turbo']=\"qwen-turbo\"\n        self.models_map['Ali-qwen-plus']=\"qwen-plus\"\n        self.models_map['Ali-qwen-max']=\"qwen-max\"\n        self.models_map['Ali-qwen-1.8b-chat']=\"qwen-1.8b-chat\"\n        self.models_map['Ali-qwen-7b-chat']=\"qwen-7b-chat\"\n        self.models_map['Ali-qwen-14b-chat']=\"qwen-14b-chat\"\n        self.models_map['Ali-qwen-72b-chat'] =\"qwen-72b-chat\"        \n        self.models_map['Ali-chatglm-6b-v2']=\"chatglm-6b-v2\"\n        self.models_map['Ali-chatglm3-6b']=\"chatglm3-6b\"\n        self.models_map['Ali-baichuan-7b-v1']=\"baichuan-7b-v1\"        \n        self.models_map['Ali-baichuan2-7b-chat-v1']=\"baichuan2-7b-chat-v1\"\n        #self.models_map['Ali-dolly-12b-v2']=\"dolly-12b-v2\"\n\n    def models(self):\n        return self.models_map.keys()\n        \n    def request(self,question,model_name): \n        import dashscope\n        from http import HTTPStatus\n        dashscope.api_key=os.getenv(\"DASHSCOPE_API_KEY\")\n    \n        if model_name not in self.models_map:\n            logger.info(\"not find\")\n            return None\n        for i in range(2):\n            fp = StringIO()\n            try:\n                if model_name in [\"Ali-chatglm-6b-v2\",\"Ali-baichuan-7b-v1\",\"Ali-dolly-12b-v2\"]:\n\n                    if model_name in [\"Ali-baichuan-7b-v1\",\"Ali-dolly-12b-v2\"]:\n                        response = dashscope.Generation.call(\n                            model=self.models_map[model_name],\n                            prompt=question\n                        )                  \n                    else:\n                        response = dashscope.Generation.call(\n                            model=self.models_map[model_name],\n                            prompt=question,\n                            history=[]\n                        )\n                    if response.status_code == HTTPStatus.OK:\n                        return model_name,response.output['text']\n                    else:\n                        logger.info('Request id: %s, Status code: %s, error code: %s, error message: %s' % (\n                            response.request_id, response.status_code,\n                            response.code, response.output\n                        ))\n                        time.sleep(10)                    \n                else:\n                    response = dashscope.Generation.call(\n                        model=self.models_map[model_name],\n                        prompt=question,\n                        seed=1234,\n                        top_p=0.85,\n                        top_k=4,\n                        result_format='message',\n                        enable_search=False,\n                        #max_tokens=1500,\n                        temperature=0.1,\n                        repetition_penalty=1.0,\n                        stream=False\n                    )\n                    if response.status_code == HTTPStatus.OK:\n                        return model_name,response.output.choices[0]['message']['content']\n                    else:\n                        logger.info('Request id: %s, Status code: %s, error code: %s, error message: %s' % (\n                            response.request_id, response.status_code,\n                            response.code, response.message\n                        ))\n                        time.sleep(10)\n            except:\n                traceback.print_exc(file=fp)\n                print(fp.getvalue())\n                time.sleep(10)\n        return None\n\nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=AliLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Ali-qwen-max') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n llm python=3.7\nconda activate llm\npip install python-dotenv requests dashscope\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-python\">\u5728Python\u4e2d\uff0c\u4f60\u53ef\u4ee5\u4f7f\u7528OpenCV\u548cmoviepy\u5e93\u6765\u5b9e\u73b0\u8fd9\u4e2a\u9700\u6c42\u3002\u4f46\u662f\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0cOpenCV\u5e76\u4e0d\u76f4\u63a5\u652f\u6301RTSP\u6d41\u7684\u97f3\u9891\u4fdd\u5b58\uff0c\u6240\u4ee5\u8fd9\u91cc\u53ea\u5904\u7406\u89c6\u9891\u90e8\u5206\u3002\u5bf9\u4e8e\u97f3\u9891\u90e8\u5206\uff0c\u4f60\u53ef\u80fd\u9700\u8981\u7ed3\u5408\u5176\u4ed6\u5e93\u5982gstreamer\u6216\u8005ffmpeg\u8fdb\u884c\u66f4\u6df1\u5ea6\u7684\u5f00\u53d1\u3002\u4ee5\u4e0b\u662f\u4e00\u4e2a\u7b80\u5316\u7684\u793a\u4f8b\uff1a\n\n\u200b```python\nimport cv2\nimport time\nfrom moviepy.editor import VideoFileClip\n\n# 1. \u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e\ncap = cv2.VideoCapture('rtsp:\/\/your_rtsp_stream')\n\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')  # \u4f7f\u7528mp4v\u7f16\u89e3\u7801\u5668\n\ncurrent_file_index = 0\nstart_time = time.time()\n\nwhile True:\n    ret, frame = cap.read()\n    \n    if not ret:\n        break\n\n    # 2. \u5c06\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f\n    current_time = time.time()\n    duration = current_time - start_time\n\n    if duration > 300:  # \u5f53\u8d85\u8fc75\u5206\u949f\uff08300\u79d2\uff09\n        if cv2.waitKey(1) & 0xFF == ord('q'):  # \u68c0\u67e5\u662f\u5426\u6309\u4e0b'q'\u952e\u9000\u51fa\n            break\n        \n        # \u5173\u95ed\u5f53\u524d\u6587\u4ef6\u5e76\u521b\u5efa\u65b0\u6587\u4ef6\n        out.release()\n        current_file_index += 1\n        file_name = f\"output_{current_file_index}.mp4\"\n        out = cv2.VideoWriter(file_name, fourcc, 20.0, (frame.shape[1], frame.shape[0]))  # \u5047\u8bbe\u5e27\u7387\u4e3a20fps\n        start_time = current_time\n    \n    # \u5199\u5165\u89c6\u9891\u5e27\u5230\u5f53\u524d\u7684VideoWriter\u5bf9\u8c61\n    out.write(frame)\n\n    # \u5728\u8fd9\u91cc\u6dfb\u52a0\u5173\u952e\u5e27\u68c0\u6d4b\u903b\u8f91\uff0c\u4f46OpenCV\u5e76\u6ca1\u6709\u76f4\u63a5\u63d0\u4f9b\u5173\u952e\u5e27\u68c0\u6d4bAPI\uff0c\n    # \u901a\u5e38\u9700\u8981\u901a\u8fc7FFmpeg\u6216\u5176\u4ed6\u65b9\u5f0f\u89e3\u6790H.264\u7b49\u7f16\u7801\u7684NALU\u5355\u5143\u83b7\u53d6\u5173\u952e\u5e27\u4fe1\u606f\u3002\n\n# \u91ca\u653e\u8d44\u6e90\ncap.release()\nout.release()\n\n# 3. \u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n# \u8fd9\u90e8\u5206\u8f83\u4e3a\u590d\u6742\uff0c\u901a\u5e38\u4f1a\u501f\u52a9ffmpeg\u547d\u4ee4\u884c\u5de5\u5177\u5b8c\u6210\uff0cPython\u4e2d\u53ef\u4ee5\u8c03\u7528os.system\u6267\u884c\u547d\u4ee4\uff1a\n# os.system(\"ffmpeg -re -i output.mp4 -c copy -f flv rtmp:\/\/127.0.0.1\/live\")\n\n# \u82e5\u8981\u5728Python\u4e2d\u5b8c\u5168\u63a7\u5236\u63a8\u6d41\u8fc7\u7a0b\uff0c\u53ef\u4ee5\u4f7f\u7528\u8bf8\u5982libav\u6216pyav\u8fd9\u6837\u7684\u5e93\uff0c\u4f46\u8fd9\u8d85\u51fa\u4e86\u672c\u95ee\u9898\u7684\u8303\u56f4\u3002\n\u200b```\n\n\u6ce8\u610f\uff1a\u4e0a\u8ff0\u4ee3\u7801\u4ec5\u5904\u7406\u4e86\u89c6\u9891\u5f55\u5236\u4e0e\u5206\u6bb5\u5b58\u50a8\u7684\u90e8\u5206\uff0c\u5e76\u672a\u6d89\u53ca\u97f3\u9891\u53caRTMP\u63a8\u9001\uff0c\u5b9e\u9645\u9879\u76ee\u4e2d\u53ef\u80fd\u9700\u8981\u914d\u5408FFmpeg\u6216\u5176\u4ed6\u5de5\u5177\u5b8c\u6210\u5168\u90e8\u529f\u80fd\u3002\n<\/code><\/pre>\n<h2><a id=\"%E6%98%9F%E7%81%AB\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>\u661f\u706b<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\nimport _thread as thread\nimport base64\nimport datetime\nimport hashlib\nimport hmac\nimport json\nfrom urllib.parse import urlparse\nimport ssl\nfrom datetime import datetime\nfrom time import mktime\nfrom urllib.parse import urlencode\nfrom wsgiref.handlers import format_date_time\nimport websocket  # \n\nanswer = \"\"\n\nclass Ws_Param(object):\n    # \u521d\u59cb\u5316\n    def __init__(self, APPID, APIKey, APISecret, Spark_url):\n        self.APPID = APPID\n        self.APIKey = APIKey\n        self.APISecret = APISecret\n        self.host = urlparse(Spark_url).netloc\n        self.path = urlparse(Spark_url).path\n        self.Spark_url = Spark_url\n\n    # \u751f\u6210url\n    def create_url(self):\n        # \u751f\u6210RFC1123\u683c\u5f0f\u7684\u65f6\u95f4\u6233\n        now = datetime.now()\n        date = format_date_time(mktime(now.timetuple()))\n\n        # \u62fc\u63a5\u5b57\u7b26\u4e32\n        signature_origin = \"host: \" + self.host + \"\\n\"\n        signature_origin += \"date: \" + date + \"\\n\"\n        signature_origin += \"GET \" + self.path + \" HTTP\/1.1\"\n\n        # \u8fdb\u884chmac-sha256\u8fdb\u884c\u52a0\u5bc6\n        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),\n                                 digestmod=hashlib.sha256).digest()\n\n        signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')\n\n        authorization_origin = f'api_key=\"{self.APIKey}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{signature_sha_base64}\"'\n\n        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')\n\n        # \u5c06\u8bf7\u6c42\u7684\u9274\u6743\u53c2\u6570\u7ec4\u5408\u4e3a\u5b57\u5178\n        v = {\n            \"authorization\": authorization,\n            \"date\": date,\n            \"host\": self.host\n        }\n        # \u62fc\u63a5\u9274\u6743\u53c2\u6570\uff0c\u751f\u6210url\n        url = self.Spark_url + '?' + urlencode(v)\n        # \u6b64\u5904\u6253\u5370\u51fa\u5efa\u7acb\u8fde\u63a5\u65f6\u5019\u7684url,\u53c2\u8003\u672cdemo\u7684\u65f6\u5019\u53ef\u53d6\u6d88\u4e0a\u65b9\u6253\u5370\u7684\u6ce8\u91ca\uff0c\u6bd4\u5bf9\u76f8\u540c\u53c2\u6570\u65f6\u751f\u6210\u7684url\u4e0e\u81ea\u5df1\u4ee3\u7801\u751f\u6210\u7684url\u662f\u5426\u4e00\u81f4\n        return url\n\n# \u6536\u5230websocket\u9519\u8bef\u7684\u5904\u7406\ndef on_error(ws, error):\n    print(\"### error:\", error)\n\n# \u6536\u5230websocket\u5173\u95ed\u7684\u5904\u7406\ndef on_close(ws,one,two):\n    print(\" \")\n\n# \u6536\u5230websocket\u8fde\u63a5\u5efa\u7acb\u7684\u5904\u7406\ndef on_open(ws):\n    thread.start_new_thread(run, (ws,))\n\ndef run(ws, *args):\n    data = json.dumps(gen_params(appid=ws.appid, domain= ws.domain,question=ws.question))\n    ws.send(data)\n\n# \u6536\u5230websocket\u6d88\u606f\u7684\u5904\u7406\ndef on_message(ws, message):\n    # print(message)\n    data = json.loads(message)\n    code = data['header']['code']\n    if code != 0:\n        print(f'\u8bf7\u6c42\u9519\u8bef: {code}, {data}')\n        ws.close()\n    else:\n        choices = data[\"payload\"][\"choices\"]\n        status = choices[\"status\"]\n        content = choices[\"text\"][0][\"content\"]\n        #print(content,end =\"\")\n        global answer\n        answer += content\n        # print(1)\n        if status == 2:\n            ws.close()\n            \ndef gen_params(appid, domain,question):\n    \"\"\"\n    \u901a\u8fc7appid\u548c\u7528\u6237\u7684\u63d0\u95ee\u6765\u751f\u6210\u8bf7\u53c2\u6570\n    \"\"\"\n    data = {\n        \"header\": {\n            \"app_id\": appid,\n            \"uid\": \"1234\"\n        },\n        \"parameter\": {\n            \"chat\": {\n                \"domain\": domain,\n                \"temperature\": 0.1,\n                \"top_k\":4,\n                \"max_tokens\": 2048,#\n                \"auditing\": \"default\"\n            }\n        },\n        \"payload\": {\n            \"message\": {\n                \"text\": question\n            }\n        }\n    }\n    return data\n    \n\ndef SparkAPI(appid, api_key, api_secret, Spark_url,domain, question):\n    wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)\n    websocket.enableTrace(False)\n    wsUrl = wsParam.create_url()\n    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)\n    ws.appid = appid\n    ws.question = question\n    ws.domain = domain\n    ws.run_forever(sslopt={\"cert_reqs\": ssl.CERT_NONE})\n    \nclass XfLLMs(object):\n    '''\n    https:\/\/www.xfyun.cn\/doc\/spark\/Web.html#_1-\u63a5\u53e3\u8bf4\u660e\n    '''\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Xf-Spark-v1.5']={\"domain\":\"general\",\"url\":\"ws:\/\/spark-api.xf-yun.com\/v1.1\/chat\"}\n        self.models_map['Xf-Spark-v3.1']={\"domain\":\"generalv3\",\"url\":\"ws:\/\/spark-api.xf-yun.com\/v3.1\/chat\"}\n\n    def models(self):\n        return self.models_map.keys()\n\n    def _get_text(self,role, content):#\n        jsoncon = {}\n        jsoncon[\"role\"] = role\n        jsoncon[\"content\"] = content\n        return jsoncon\n\n    def _get_length(self,text):\n        length = 0\n        for content in text:\n            temp = content[\"content\"]\n            leng = len(temp)\n            length += leng\n        return length\n\n    def _check_len(self,text):\n        while self._get_length(text) > 8000:\n            del text[0]\n        return text\n\n    def request(self,question,model_name): \n        global answer\n        appid = os.getenv(\"APP_ID\")\n        api_secret = os.getenv(\"API_SECRET\")\n        api_key = os.getenv(\"API_KEY\")\n    \n        if model_name not in self.models_map:\n            logger.info(\"not find\")\n            return None\n        for i in range(2):\n            fp = StringIO()\n            try:                \n                text = []\n                question = self._check_len([self._get_text(\"user\", question)])\n                answer = \"\"\n                SparkAPI(\n                    appid,\n                    api_key,\n                    api_secret,\n                    self.models_map[model_name]['url'],\n                    self.models_map[model_name]['domain'],\n                    question,\n                )\n                text.clear()\n                return model_name,answer\n            except:\n                traceback.print_exc(file=fp)\n                print(fp.getvalue())\n                time.sleep(10)\n        return None\n\nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=XfLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Xf-Spark-v3.1') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n llm python=3.7\nconda activate llm\npip install python-dotenv requests\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-python\">```python\nimport cv2\nimport numpy as np\nimport time\nimport subprocess\n\ndef receive_rtsp_data(rtsp_url):\n    cap = cv2.VideoCapture(rtsp_url)\n    return cap\n\ndef save_video_to_mp4(cap, output_path):\n    fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n    out = cv2.VideoWriter(output_path, fourcc, 30.0, (int(cap.get(3)), int(cap.get(4))))\n    return out\n\ndef process_video(cap, out):\n    frame_count = 0\n    start_time = time.time()\n    while cap.isOpened():\n        ret, frame = cap.read()\n        if not ret:\n            break\n\n        frame_count += 1\n        out.write(frame)\n\n        if frame_count % 1800 == 0:  # Check every 3 seconds for keyframe\n            keyframe_detected = detect_keyframe(frame)\n            if keyframe_detected:\n                out.release()\n                break\n\n        current_time = time.time()\n        if current_time - start_time > 5 * 60:  # 5 minutes\n            out.release()\n            break\n\ndef detect_keyframe(frame):\n    # This is a simple example of keyframe detection using color histogram\n    hist = cv2.calcHist([frame], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])\n    hist = cv2.normalize(hist, hist).flatten()\n    return np.max(hist) > 255 \/ 4\n\ndef push_to_rtmp(output_path):\n    cmd = f\"ffmpeg -re -i {output_path} -c copy -f flv rtmp:\/\/127.0.0.1\/live\"\n    subprocess.call(cmd, shell=True)\n\nif __name__ == \"__main__\":\n    rtsp_url = \"rtsp:\/\/your_rtsp_url\"\n    output_path = \"output.mp4\"\n\n    cap = receive_rtsp_data(rtsp_url)\n    out = save_video_to_mp4(cap, output_path)\n    process_video(cap, out)\n    push_to_rtmp(output_path)\n\n    cap.release()\n    out.release()\n\u200b```\n<\/code><\/pre>\n<h2><a id=\"%E7%99%BE%E5%B7%9D\" class=\"anchor\" aria-hidden=\"true\"><span class=\"octicon octicon-link\"><\/span><\/a>\u767e\u5ddd<\/h2>\n<p><strong>\u4ee3\u7801<\/strong><\/p>\n<pre><code class=\"language-python\">import os\nfrom dotenv import load_dotenv\nload_dotenv(dotenv_path = \".env\",override = True)\nimport requests\nimport json\nimport time\nimport sys,traceback\nfrom io import StringIO\nimport re\n\nclass BaichuanLLMs(object):\n    '''\n    https:\/\/platform.baichuan-ai.com\/docs\/api\n    '''\n    def __init__(self):\n        self.models_map={}\n        self.models_map['Baichuan2-Turbo']=\"Baichuan2-Turbo\"\n        self.models_map['Baichuan2-Turbo-192k']=\"Baichuan2-Turbo-192k\"\n    \n    def models(self):\n        return self.models_map.keys()\n        \n    def request(self,question,model_name): \n        if model_name not in self.models_map:\n            return None\n        url = \"https:\/\/api.baichuan-ai.com\/v1\/chat\/completions\"\n        api_key = os.getenv(\"BAICHUAN_KEY\")\n        data = {\n            \"model\": self.models_map[model_name],\n            \"messages\": [\n                {\n                    \"role\": \"user\",\n                    \"content\": question\n                }\n            ],\n            \"stream\": False,\n            \"top_p\":0.85,\n            \"top_k\":4,\n            \"temperature\":0.1,\n            \"with_search_enhance\":False\n        }\n        json_data = json.dumps(data)\n        headers = {\n            \"Content-Type\": \"application\/json\",\n            \"Authorization\": \"Bearer \" + api_key\n        }\n        for i in range(2):\n            fp = StringIO()\n            try:\n                response = requests.post(url, data=json_data, headers=headers, timeout=60)\n                if response.status_code == 200:\n                    return model_name,response.json()['choices'][0]['message'][\"content\"]\n                else:\n                    logger.info(\"\u8bf7\u6c42\u5931\u8d25,\u72b6\u6001\u7801:\", response.status_code)\n                    logger.info(\"\u8bf7\u6c42\u5931\u8d25,body:\", response.text)   \n                    time.sleep(10)\n            except:\n                traceback.print_exc(file=fp)\n                logger.info(fp.getvalue())\n                time.sleep(10)\n        return None\n\nquestion=u'''\n\u91c7\u7528python\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:\n1.\u63a5\u6536rtsp\u97f3\u89c6\u9891\u6570\u636e \n2.\u5c06\u97f3\u89c6\u9891\u4fdd\u5b58\u4e3amp4\u683c\u5f0f \n3.\u5f53mp4\u6587\u4ef6\u7684\u65f6\u957f\u8d85\u8fc75\u5206\u949f\uff0c\u4e14\u9047\u5230\u5173\u952e\u5e27\u65f6\uff0c\u5173\u95ed\u8be5\u6587\u4ef6\uff0c\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\n4.\u5c06\u97f3\u89c6\u9891\u63a8\u9001\u5230rtmp:\/\/127.0.0.1\/live\n'''\n\ninfer=BaichuanLLMs()\nfor model_name in infer.models(): \n    result=infer.request(question,'Baichuan2-Turbo') \n    if result:\n        name,content=result\n        with open(\"{}.txt\".format(name),\"w\") as f:\n            f.write(content)\n    break\n<\/code><\/pre>\n<p><strong>\u8fd0\u884c<\/strong><\/p>\n<pre><code class=\"language-shell\">conda create -n llm python=3.7\nconda activate llm\npip install python-dotenv requests\npython llm.py\n<\/code><\/pre>\n<p><strong>\u8f93\u51fa<\/strong><\/p>\n<pre><code class=\"language-shell\">{\"error\":{\"code\":\"insufficient_quota\",\"param\":null,\"type\":\"insufficient_quota\",\"message\":\"You exceeded your current quota, please check your plan and billing details.\"}}\n\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u8d85\u5168\u603b\u7ed3\uff01\u5404\u7c7b\u5927\u6a21\u578b\u5bf9\u8bddREST API\u8c03\u7528 \u672c\u6587\u6574\u7406\u4e86\u4e3b\u8981\u51e0\u4e2a\u5927\u6a21\u578b\u63d0\u4f9b\u5546\u7684REST API \u7528\u6cd5\uff0c\u65b9\u4fbf\u5b66\u4e60 [&hellip;]<\/p>\n","protected":false},"author":9,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[99],"tags":[],"class_list":["post-48506","post","type-post","status-publish","format-standard","hentry","category-javabase"],"_links":{"self":[{"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/posts\/48506","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/comments?post=48506"}],"version-history":[{"count":1,"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/posts\/48506\/revisions"}],"predecessor-version":[{"id":48507,"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/posts\/48506\/revisions\/48507"}],"wp:attachment":[{"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/media?parent=48506"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/categories?post=48506"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/wx.kaifamiao.info\/index.php\/wp-json\/wp\/v2\/tags?post=48506"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}