-
Notifications
You must be signed in to change notification settings - Fork 438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
FEAT: Gradio HiTL Scorer #722
Open
mart123p
wants to merge
17
commits into
Azure:main
Choose a base branch
from
mart123p:feature/gradio-scorer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
f62e992
Added gradio scorer implementation
c5a24d5
Added missing export
b1df059
Fixed a few issues with PyRIT integration
829532d
Fixed a typo
1499dc2
Fixed a typing issue
2557cfd
Fixed import errors
3ba7ca6
Changed global import to scoped import
53b9b9c
Fixed an import issue
4e279b1
Added HumanInTheLoopScorerGradio to doc
6616eee
Added missing copyright
mart123p 0970314
Added docstring to constructor
mart123p 9a45e55
Changed RPC capitalization
mart123p bf0931e
Added RPC code description
mart123p e9959be
Added a comment about Gradio aiofiles dependency
mart123p ff7b5fb
Changed coding style for private members
mart123p 4941211
Extracted button click logic
mart123p b4eb898
Changed functions to use kw-only args
mart123p File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT license. | ||
|
||
import asyncio | ||
from pyrit.score.scorer import Scorer | ||
from pyrit.models import Score, PromptRequestPiece | ||
from typing import Optional | ||
|
||
class HumanInTheLoopScorerGradio(Scorer): | ||
""" | ||
Create scores from manual human input using Gradio and adds them to the database. | ||
|
||
Parameters: | ||
scorer (Scorer): The scorer to use for the initial scoring. | ||
re_scorers (list[Scorer]): The scorers to use for re-scoring. | ||
open_browser(bool): The scorer will open the Gradio interface in a browser instead of opening it in PyWebview | ||
""" | ||
|
||
def __init__(self, *, open_browser=False, scorer: Scorer = None, re_scorers: list[Scorer] = None) -> None: | ||
# Import here to avoid importing rpyc in the main module that might not be installed | ||
from pyrit.ui.rpc import AppRPCServer | ||
|
||
self._scorer = scorer | ||
self._re_scorers = re_scorers | ||
self._rpc_server = AppRPCServer(open_browser=open_browser) | ||
self._rpc_server.start() | ||
|
||
|
||
async def score_async(self, request_response: PromptRequestPiece, *, task: Optional[str] = None) -> list[Score]: | ||
try: | ||
return await asyncio.to_thread(self.score_prompt_manually, request_response, task=task) | ||
except asyncio.CancelledError: | ||
self._rpc_server.stop() | ||
raise | ||
|
||
|
||
def score_prompt_manually(self, request_prompt: PromptRequestPiece, *, task: Optional[str] = None) -> list[Score]: | ||
self._rpc_server.wait_for_client() | ||
self._rpc_server.send_score_prompt(request_prompt) | ||
score = self._rpc_server.wait_for_score() | ||
return [score] | ||
|
||
def validate(self, request_response: PromptRequestPiece, *, task: Optional[str] = None): | ||
pass | ||
|
||
def __del__(self): | ||
self._rpc_server.stop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT license. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT license. | ||
|
||
import os | ||
mart123p marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import sys | ||
import subprocess | ||
import traceback | ||
|
||
GLOBAL_MUTEX_NAME = "PyRIT-Gradio" | ||
|
||
def launch_app(open_browser=False): | ||
# Launch a new process to run the gradio UI. | ||
# Locate the python executable and run this file. | ||
current_path = os.path.abspath(__file__) | ||
python_path = sys.executable | ||
|
||
# Start a new process to run it | ||
subprocess.Popen([python_path, current_path, str(open_browser)], creationflags=subprocess.CREATE_NEW_CONSOLE) | ||
|
||
def is_app_running(): | ||
if sys.platform != "win32": | ||
raise NotImplementedError("This function is only supported on Windows.") | ||
return True | ||
|
||
import ctypes.wintypes | ||
|
||
SYNCHRONIZE = 0x00100000 | ||
mutex = ctypes.windll.kernel32.OpenMutexW(SYNCHRONIZE, False, GLOBAL_MUTEX_NAME) | ||
if not mutex: | ||
return False | ||
|
||
# Close the handle to the mutex | ||
ctypes.windll.kernel32.CloseHandle(mutex) | ||
return True | ||
|
||
if __name__ == "__main__": | ||
def create_mutex(): | ||
if sys.platform != "win32": | ||
raise NotImplementedError("This function is only supported on Windows.") | ||
|
||
# TODO make sure to add cross-platform support for this. | ||
mart123p marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import ctypes.wintypes | ||
mutex = ctypes.windll.kernel32.CreateMutexW(None, False, GLOBAL_MUTEX_NAME) | ||
last_error = ctypes.windll.kernel32.GetLastError() | ||
if last_error == 183: # ERROR_ALREADY_EXISTS | ||
return False | ||
return True | ||
|
||
if not create_mutex(): | ||
print("Gradio UI is already running.") | ||
sys.exit(1) | ||
print("Starting Gradio Interface please wait...") | ||
try: | ||
open_browser = False | ||
if len(sys.argv) > 1: | ||
open_browser = sys.argv[1] == "True" | ||
|
||
from scorer import GradioApp | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm guessing this is here so that we don't import it if the gradio extra isn't installed? If so, we import gradio in the scorer file. So that won't help, right? |
||
app = GradioApp() | ||
app.start_gradio(open_browser=open_browser) | ||
except: | ||
# Print the error message and traceback | ||
print(traceback.format_exc()) | ||
input("Press Enter to exit.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT license. | ||
|
||
import gradio as gr | ||
|
||
from rpc_client import RPCClient | ||
|
||
class ConnectionStatusHandler: | ||
def __init__(self, | ||
is_connected_state: gr.State, | ||
rpc_client: RPCClient): | ||
self.state = is_connected_state | ||
self.server_disconnected = False | ||
self.rpc_client = rpc_client | ||
self.next_prompt = "" | ||
|
||
def setup(self, *, main_interface: gr.Column, loading_animation: gr.Column, next_prompt_state: gr.State): | ||
self.state.change(fn=self._on_state_change, inputs=[self.state], outputs=[main_interface, loading_animation, next_prompt_state]) | ||
|
||
connection_status_timer = gr.Timer(1) | ||
connection_status_timer.tick( | ||
fn=self._check_connection_status, | ||
inputs=[self.state], | ||
outputs=[self.state] | ||
).then( | ||
fn=self._reconnect_if_needed, | ||
outputs=[self.state] | ||
) | ||
|
||
def set_ready(self): | ||
self.server_disconnected = False | ||
|
||
def set_disconnected(self): | ||
self.server_disconnected = True | ||
|
||
def set_next_prompt(self, next_prompt: str): | ||
self.next_prompt = next_prompt | ||
|
||
def _on_state_change(self, is_connected: bool): | ||
print("Connection status changed to: ", is_connected, " - ", self.next_prompt) | ||
if is_connected: | ||
return [gr.Column(visible=True), gr.Row(visible=False), self.next_prompt] | ||
return [gr.Column(visible=False), gr.Row(visible=True), self.next_prompt] | ||
|
||
def _check_connection_status(self, is_connected: bool): | ||
if self.server_disconnected or not is_connected: | ||
print("Gradio disconnected") | ||
return False | ||
return True | ||
|
||
def _reconnect_if_needed(self): | ||
if self.server_disconnected: | ||
print("Attempting to reconnect") | ||
self.rpc_client.reconnect() | ||
prompt = self.rpc_client.wait_for_prompt() | ||
self.next_prompt = str(prompt.original_value) | ||
self.server_disconnected = False | ||
return True |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The class or constructor needs a docstring