Using Sahi

Using Sahi -

Before you start - Prerequisites
Java 1.5 or above is needed for running Sahi.

Download Sahi
Download Sahi V3 (2009-11-30) from SourceForge

Install Sahi
Unzip sahi.zip to a desired location

Start proxy of Sahi:

Windows: - Go to <sahi_root>/userdata/bin and run start_sahi.bat
Linux - Go to <sahi_root>/userdata/bin and run start_sahi.sh

Note that by default Sahi uses port 9999. This can be modified through sahi.properties

Configure the browser:
You need to change your browser's proxy setting to use Sahi's proxy.

Firefox:

  • Go to Tools > Options >Advanced >Network> Connection Settings >
  • Set to "Manual Proxy Configuration"
  • Set "HTTP Proxy" to "localhost"
  • Set "Port" to "9999". (This setting can be modified through /config/sahi.properties)
  • Do the same for "SSL Proxy" too, if you wish to record and playback https sites
  • Keep "Use the same proxy for all protocol" unchecked as Sahi does not understand protocols other than HTTP
  • NOTE: "No Proxy for" should NOT have localhost in it.

Internet Explorer:

  • Go to Tools > Internet Options > Connections > LAN Settings >
  • In "Proxy server" section, Check "Use a proxy server for your LAN"
  • Click on "Advanced"
  • For HTTP: set "Proxy address to use" to "localhost" and set "Port" to "9999"
  • For Secure: set "Proxy address to use" to "localhost" and set "Port" to "9999" (if you want to test https sites too)
  • Clear out anything in "Do not use proxy server for addresses beginning with:"
  • OK
  • Leave "Bypass proxy server for local addresses" unchecked
  • OK > OK

Recording through Sahi

  • Press ALT and double click on the window which you want to record. Sahi's Controller window will pop up. (If that does not work, press CTRL and ALT keys together and then double click. Make sure popup blockers are turned off. For further trouble shooting have a look at this help link.)
  • On the Controller, go the the Record tab (would be selected by default).
  • Give a name for the script, and click 'Record'
  • Navigate on your website like you normally would. Most actions on the page will now get recorded.
  • Add an assertion:
    o Move the mouse over any html element while pressing Ctrl key. The Accessor field will get populated in the Controller.
    o Click the "Assert" button to generate assertions for the element. They will appear in the "Evaluate Expression" box.
    o Click "Test --->" to check that the assertions are true. You can evaluate any javascript using "Evaluate Expression" and "Test --->". Actions performed via the Controller will not be automatically recorded. Only actions performed directly on the page are automatically recorded. This lets you experiment on the webpage at recording time with out impacting the script.
    o Once satisfied, click on "Append to Script". This will add the assertions to the Script.
  • Click "Stop" to finish recording.

Note that the Controller can be closed and reopened at any time, without disrupting recording.

View the recorded script

The recoded script can be viewed and edited by opening the .sah file in the <sahi_root>/userdata/scripts directory. Sahi scripts are simple text files which use Javascript syntax.

The script can be edited even while recording, so that logical segregation into functions etc. can be done as recording happens.

Playing back

  • Open the Sahi Controller (ALT-DblClick on the page).
  • Enter the script name in the "File:" field (with the help of the autocompletion feature).
  • Enter the Start URL of the test. If you had started recording from http://www.google.co.in , use that URL.
  • Click 'Set'.
  • Wait for the page to reload.
  • Click 'Play'.

Steps will start executing, and the Controller will be updated accordingly. Once finished, SUCCESS or FAILURE will be displayed at the end of the steps.

Note that the Controller can be closed at any time, without disrupting playback.

View Logs

On the Controller, go to Playback tab and click on "View Logs" link at the bottom right. It will open a window with the results neatly formatted in HTML.

Clicking on a line in the logs will drill down to exact line in script.

You can also view the logs at http://localhost:9999/logs

That is it! You have successfully recorded and played back a Sahi script!

Help! The Sahi Controller does not come up

The controller will only come up if the web page has been modified by the Sahi proxy

Try the following:

  • Refresh the browser and check
  • Force Reload (override cache),
    Firefox: Ctrl+F5 or Ctrl+Shift+R Internet Explorer: Ctrl + F5
    or Clear the browser cache manually and reload.
  • Make sure popup blockers are turned off.
  • If you are surfing the intranet on IE:
    Go to Tools -> Internet Options -> Connections -> LAN Settings. There, make sure that "Bypass proxy for local addresses" is unchecked.

Configuration Sahi and improve test speed

  • Replace sahi.bat with the one attached.
  • Modify sahi.bat and setup JAVA_HOME, using jdk6 will have better performance.
  • Add the sahi-patch.jar to %SAHI_HOME%/lib
    • You can download sahi.bat and sahi-patch.jar

Sahi script

  • 验证用户名和密码
    function Test($username, $password){ _setValue(_textbox("j_username"), $username); _setValue(_password("j_password"), $password); }
    Test("root", "root")
    _click(_submit("Login"));
  • 包含另一个脚本文件
    _include("path/common_functions.sah");
  • 定义变量名并赋值
    var $variableName = value;
    OR
    var $variableName;
    $variableName = value;
  • 在控制台打印信息
    function printThroughJava(s){ Packages.java.lang.System.out.println("Through Java: " + s); }
    printThroughJava("Hi there");
    //将在控制台打印出Through Java: Hi there
  • if条件语句
    var $i = 2;
    if($i == 1){ Packages.java.lang.System.out.println("i = " + $i); }else{ Packages.java.lang.System.out.println("i = " + $i); }
    }
  • for循环语句
    /*This loop will login with user1, password1, user2, password2 etc.
    login and logout are custom functions.*/
    var $max = 10;
    for(var $i=0; $i<$max; $i++){ Packages.java.lang.System.out.println("i = " + $i); }

    * while循环语句
    $i = 0;
    while ($i++ < 10) { Packages.java.lang.System.out.println("i = " + $i); }
    }
  • 捕捉异常
    try{ _click(_link("does not exist")); }catch(e){
    _log("exception occur"); //显示此行并执行下一句
    //_logException(e);//不显示任何信息
    Packages.java.lang.System.out.println("excute next step");
    $i = 0;
    while($i++ < 10){ Packages.java.lang.System.out.println("i = " + $i); }
    //_logExceptionAsFailure(e);//提示失败
    }
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse from pathlib import Path import cv2 from sahi import AutoDetectionModel from sahi.predict import get_sliced_prediction from sahi.utils.ultralytics import download_yolo11n_model from ultralytics.utils.files import increment_path from ultralytics.utils.plotting import Annotator, colors class SAHIInference: """ Runs Ultralytics YOLO11 and SAHI for object detection on video with options to view, save, and track results. This class integrates SAHI (Slicing Aided Hyper Inference) with YOLO11 models to perform efficient object detection on large images by slicing them into smaller pieces, running inference on each slice, and then merging the results. Attributes: detection_model (AutoDetectionModel): The loaded YOLO11 model wrapped with SAHI functionality. Methods: load_model: Loads a YOLO11 model with specified weights. inference: Runs object detection on a video using the loaded model. parse_opt: Parses command line arguments for the inference process. """ def __init__(self): """Initializes the SAHIInference class for performing sliced inference using SAHI with YOLO11 models.""" self.detection_model = None def load_model(self, weights: str) -> None: """ Load a YOLO11 model with specified weights for object detection using SAHI. Args: weights (str): Path to the model weights file. """ yolo11_model_path = f"models/{weights}" download_yolo11n_model(yolo11_model_path) # Download model if not present self.detection_model = AutoDetectionModel.from_pretrained( model_type="ultralytics", model_path=yolo11_model_path, device="cpu" ) def inference( self, weights: str = "yolo11n.pt", source: str = "test.mp4", view_img: bool = False, save_img: bool = False, exist_ok: bool = False, ) -> None: """ Run object detection on a video using YOLO11 and SAHI. The function processes each frame of the video, applies sliced inference using SAHI, and optionally displays and/or saves the results with bounding boxes and labels. Args: weights (str): Model weights path. source (str): Video file path. view_img (bool): Whether to display results in a window. save_img (bool): Whether to save results to a video file. exist_ok (bool): Whether to overwrite existing output files. """ # Video setup cap = cv2.VideoCapture(source) assert cap.isOpened(), "Error reading video file" frame_width, frame_height = int(cap.get(3)), int(cap.get(4)) # Output setup save_dir = increment_path(Path("ultralytics_results_with_sahi") / "exp", exist_ok) save_dir.mkdir(parents=True, exist_ok=True) video_writer = cv2.VideoWriter( str(save_dir / f"{Path(source).stem}.avi"), cv2.VideoWriter_fourcc(*"MJPG"), int(cap.get(5)), (frame_width, frame_height), ) # Load model self.load_model(weights) while cap.isOpened(): success, frame = cap.read() if not success: break annotator = Annotator(frame) # Initialize annotator for plotting detection results # Perform sliced prediction using SAHI results = get_sliced_prediction( frame[..., ::-1], # Convert BGR to RGB self.detection_model, slice_height=512, slice_width=512, ) # Extract detection data from results detection_data = [ (det.category.name, det.category.id, (det.bbox.minx, det.bbox.miny, det.bbox.maxx, det.bbox.maxy)) for det in results.object_prediction_list ] # Annotate frame with detection results for det in detection_data: annotator.box_label(det[2], label=str(det[0]), color=colors(int(det[1]), True)) # Display results if requested if view_img: cv2.imshow(Path(source).stem, frame) # Save results if requested if save_img: video_writer.write(frame) # Break loop if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord("q"): break # Clean up resources video_writer.release() cap.release() cv2.destroyAllWindows() def parse_opt(self) -> argparse.Namespace: """ Parse command line arguments for the inference process. Returns: (argparse.Namespace): Parsed command line arguments. """ parser = argparse.ArgumentParser() parser.add_argument("--weights", type=str, default="yolo11n.pt", help="initial weights path") parser.add_argument("--source", type=str, required=True, help="video file path") parser.add_argument("--view-img", action="store_true", help="show results") parser.add_argument("--save-img", action="store_true", help="save results") parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment") return parser.parse_args() if __name__ == "__main__": inference = SAHIInference() inference.inference(**vars(inference.parse_opt())) 注释翻译成中文
最新发布
05-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值