client_test.py 4 KB
import os
import subprocess
import time
import socket
import requests
import yaml

def is_port_open(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('127.0.0.1', port)) == 0

def main():
    port = 8085
    server_process = None
    if not is_port_open(port):
        print(f"Starting local serve_web.py server on port {port}...")
        env = os.environ.copy()
        env["PORT"] = str(port)
        server_process = subprocess.Popen(
            ["python", "serve_web.py"],
            env=env,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )
        # Wait for server to start
        for _ in range(20):
            time.sleep(0.5)
            if is_port_open(port):
                print("Server started successfully.")
                break
        else:
            print("Failed to start server.")
            if server_process:
                server_process.terminate()
            return
    else:
        print(f"Server is already running on port {port}.")

    try:
        url_upload = f"http://127.0.0.1:{port}/api/intents/upload"
        url_fuse = f"http://127.0.0.1:{port}/api/fuse"
        
        # 1. Upload the glsx intents file
        intents_path = "benchmarks/glsx/intents.yaml"
        print(f"Uploading {intents_path} to server...")
        with open(intents_path, 'rb') as f:
            files = {'file': (os.path.basename(intents_path), f, 'application/x-yaml')}
            data = {'name': 'glsx'}
            resp = requests.post(url_upload, files=files, data=data)
            
        print("Upload Response status:", resp.status_code)
        print("Upload Response payload:", resp.json())
        assert resp.status_code == 200
        assert resp.json().get("ok") is True
        
        # 2. Query the uploaded intents
        query = "询问本月新车交付数"
        print(f"Querying: '{query}' on dataset 'glsx'...")
        payload = {
            "message": query,
            "dataset": "glsx"
        }
        resp = requests.post(url_fuse, json=payload)
        print("Query Response status:", resp.status_code)
        resp_data = resp.json()
        print("Query Response payload:", resp_data)
        
        assert resp.status_code == 200
        top_intent = resp_data.get("top", {}).get("name")
        print(f"Predicted top intent: {top_intent}")
        assert top_intent == "经营指标分析"
        print("Success! Intent recognition matches expected: 经营指标分析")

        # 3. Test JSON upload method
        print("Testing JSON payload upload...")
        with open(intents_path, 'r', encoding='utf-8') as f:
            yaml_content = f.read()
        
        payload_upload = {
            "name": "glsx_json",
            "yaml_content": yaml_content
        }
        resp = requests.post(url_upload, json=payload_upload)
        print("JSON Upload Response status:", resp.status_code)
        print("JSON Upload Response payload:", resp.json())
        assert resp.status_code == 200
        assert resp.json().get("ok") is True

        # Query the JSON-uploaded dataset
        query_json = "门店运营数量"
        print(f"Querying: '{query_json}' on dataset 'glsx_json'...")
        payload_query = {
            "message": query_json,
            "dataset": "glsx_json"
        }
        resp = requests.post(url_fuse, json=payload_query)
        print("Query Response status:", resp.status_code)
        resp_data_json = resp.json()
        print("Query Response payload:", resp_data_json)
        assert resp.status_code == 200
        top_intent_json = resp_data_json.get("top", {}).get("name")
        print(f"Predicted top intent: {top_intent_json}")
        assert top_intent_json == "门店运营分析"
        print("Success! JSON upload and query verification matches expected: 门店运营分析")

    finally:
        if server_process:
            print("Stopping local server...")
            server_process.terminate()
            server_process.wait()

if __name__ == "__main__":
    main()