Spaces:
Running
Running
Download tests/test_studio.py from ciaochris/HumanTouch: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/spaces/ciaochris/HumanTouch/resolve/main/tests/test_studio.py
- Command line
-
hf download hf://spaces/ciaochris/HumanTouch/tests/test_studio.py
-
curl -L -o test_studio.py https://huggingface.co/spaces/ciaochris/HumanTouch/resolve/main/tests/test_studio.py
13.9 kB
| """Every studio control, exercised through the real Gradio callbacks with a provider double.""" | |
| import json | |
| import warnings | |
| import gradio as gr | |
| import pytest | |
| from conftest import ScriptedProvider | |
| import render | |
| from humantouch.engine import HumanTouch | |
| from humantouch.provider import ProviderError | |
| from ui import DEMO_TEXT, N_VIEWS, create_interface | |
| SOURCE = "I am writing to inform you that the pilot enrolled 48 volunteers. I think this could help, maybe. It's really, really interesting. We utilize two tools." | |
| MODEL = "The pilot enrolled 48 volunteers. This will help. It's remarkably interesting. We use two tools. Our approach is world-class." | |
| BRIDGE = DEMO_TEXT | |
| def reply(request): | |
| if request.json_mode: | |
| if '"unresolved"' in request.system: | |
| return json.dumps({'unresolved': 'What happened next.', 'options': ['And then the lights went out.', 'Nobody moved.']}) | |
| return json.dumps({'noticed': [], 'abstraction': {'description': 'Concrete.', 'evidence': 'rust and pigeons'}, | |
| 'humor': {'description': 'Dry asides.', 'evidence': 'badly, he says'}, | |
| 'imagery': {'description': 'Plain images.', 'evidence': 'not in the sample'}, 'signature_phrases': []}) | |
| return MODEL | |
| def studio(): | |
| provider = ScriptedProvider(reply) | |
| interface = create_interface(HumanTouch(provider)) | |
| handlers = {} | |
| for dependency in interface.fns.values(): | |
| if dependency.fn is not None: | |
| handlers.setdefault(dependency.fn.__name__, dependency) | |
| return interface, handlers, provider | |
| def call(handlers, name, *args): | |
| with warnings.catch_warnings(): | |
| warnings.simplefilter('ignore') | |
| return handlers[name].fn(*args) | |
| def rewrite(handlers, session=None, vp=None, ask='', keep=None, protected=''): | |
| keep = keep or ['meaning', 'claims', 'certainty', 'vocabulary', 'rhythm', 'punctuation', 'structure'] | |
| return call(handlers, 'do_rewrite', SOURCE, ask, 'light', ['grammar', 'clarity'], keep, protected, '', False, vp, session) | |
| def test_every_callback_returns_one_value_per_output(studio): | |
| _, handlers, _ = studio | |
| out = rewrite(handlers) | |
| assert len(out) == N_VIEWS == len(handlers['do_rewrite'].outputs) | |
| for name in ('do_regenerate', 'on_restore', 'on_restore_all', 'on_restore_style', 'on_recheck', 'on_version'): | |
| assert len(handlers[name].outputs) == N_VIEWS, name | |
| assert len(handlers['do_closer'].outputs) == N_VIEWS + 1 | |
| expected = {'read_text', 'pick_notice', 'understand', 'restrength', 'do_rewrite', 'do_regenerate', 'do_closer', 'on_restore', 'on_restore_all', | |
| 'on_restore_style', 'on_recheck', 'on_version', 'on_compare', 'on_question', 'on_export', 'on_demo', 'on_compose', 'on_add', | |
| 'draft_map', 'on_extract', 'on_correction', 'on_notes', 'on_upload', 'on_load', 'indicators', 'on_find', 'on_amplify'} | |
| assert expected <= set(handlers) | |
| def test_text_and_its_provenance_arrive_together(studio): | |
| _, handlers, _ = studio | |
| text, summary, warn, ledger, restore, authorship, voice, *_rest, session = rewrite(handlers) | |
| assert 'I think this could help, maybe.' in text and '48 volunteers' in text | |
| assert 'world-class' in text and 'AI-added' in authorship and 'no counterpart' in warn | |
| assert 'withheld by the meaning guard' in ledger and 'CHANGE 01' in ledger | |
| assert 'Edited, not rewritten' in summary or 'New language added' in summary | |
| assert restore['value'] and len(restore['choices']) == len(session['versions'][0]['analysis']['changes']) | |
| assert 'Authorial distance' in voice | |
| current = session['versions'][0] | |
| assert current['result'] == text and current['model_output'] == MODEL | |
| def test_restoring_edits_never_calls_the_model(studio): | |
| _, handlers, provider = studio | |
| *_, session = rewrite(handlers) | |
| before = len(provider.requests) | |
| changes = session['versions'][0]['analysis']['changes'] | |
| addition = next(c['id'] for c in changes if 'world-class' in c['revised']) | |
| kept = [c['id'] for c in changes if c['restored']] | |
| text, *_, session = call(handlers, 'on_restore', kept + [addition], None, session) | |
| assert 'world-class' not in text | |
| text, *_, session = call(handlers, 'on_restore', [], None, session) | |
| assert 'This will help' in text # the author accepted the model's certainty change by unticking | |
| text, *_, session = call(handlers, 'on_restore_all', None, session) | |
| assert ' '.join(text.split()) == SOURCE | |
| *_, session = rewrite(handlers) | |
| text, *_ = call(handlers, 'on_restore_style', None, session) | |
| assert 'really, really' in text | |
| assert len(provider.requests) == before + 1 | |
| def test_hand_edits_are_rechecked_and_labelled(studio): | |
| _, handlers, _ = studio | |
| text, *_, session = rewrite(handlers) | |
| edited = text.replace('48 volunteers', '84 volunteers') + ' I added this by hand.' | |
| new_text, summary, warn, _, _, authorship, *_ = call(handlers, 'on_recheck', edited, None, session) | |
| assert new_text == edited and 'edited by you after generation' in authorship | |
| assert 'dropped 48' in warn or '84' in warn | |
| assert call(handlers, 'on_recheck', ' ', None, session) == tuple(gr.skip() for _ in range(N_VIEWS)) | |
| def test_versions_branch_compare_and_explain(studio): | |
| _, handlers, provider = studio | |
| *_, session = rewrite(handlers) | |
| out = call(handlers, 'do_regenerate', 'Bring back "utilize". Keep the opening exactly.', '', False, None, session) | |
| text, session = out[0], out[-1] | |
| assert len(session['versions']) == 2 and session['current'] == 1 | |
| assert text.startswith('I am writing to inform you') and 'We utilize two tools.' in text | |
| assert session['versions'][1]['parent_id'] == session['versions'][0]['version_id'] | |
| assert '<current_version>' in provider.requests[-1].user | |
| back = call(handlers, 'on_version', 0, None, session) | |
| assert back[-1]['current'] == 0 and back[0] == session['versions'][0]['result'] | |
| compared = call(handlers, 'on_compare', -1, 1, None, session) | |
| assert 'Version B' in compared and 'your call' in compared | |
| assert 'withheld' in call(handlers, 'on_question', 'certainty', session) | |
| assert 'world-class' in call(handlers, 'on_question', 'added', session) | |
| session['current'] = 0 | |
| closer = call(handlers, 'do_closer', '', None, session) | |
| assert len(closer[-2]['versions']) == 3 and 'Bring this closer' in closer[-1] | |
| link = call(handlers, 'on_export', False, None, session) | |
| assert 'humantouch-provenance.json' in link | |
| assert call(handlers, 'on_export', False, None, None) == '' | |
| def test_failures_leave_previous_work_untouched(studio): | |
| interface, handlers, provider = studio | |
| *_, session = rewrite(handlers) | |
| saved = json.dumps(session, default=str) | |
| provider.replies = [ProviderError('timeout')] | |
| try: | |
| assert rewrite(handlers, session) == tuple(gr.skip() for _ in range(N_VIEWS)) | |
| assert call(handlers, 'do_regenerate', 'note', '', False, None, session) == tuple(gr.skip() for _ in range(N_VIEWS)) | |
| assert call(handlers, 'on_compose', 'A draft.', 'questions', None) == tuple(gr.skip() for _ in range(4)) | |
| finally: | |
| provider.replies = [reply] | |
| assert json.dumps(session, default=str) == saved | |
| assert call(handlers, 'do_regenerate', 'note', '', False, None, None) == tuple(gr.skip() for _ in range(N_VIEWS)) | |
| empty = call(handlers, 'do_rewrite', '', '', 'light', [], [], '', '', False, None, None) | |
| assert empty == tuple(gr.skip() for _ in range(N_VIEWS)) | |
| missing = rewrite(handlers, protected='a phrase that is not in the text') | |
| assert missing == tuple(gr.skip() for _ in range(N_VIEWS)) | |
| def test_reading_and_understanding_happen_before_editing(studio): | |
| _, handlers, provider = studio | |
| before = len(provider.requests) | |
| stats, notice = call(handlers, 'read_text', SOURCE, None) | |
| assert '26 words' in stats and notice['visible'] and any('stock phrase' in c for c in notice['choices']) | |
| assert call(handlers, 'pick_notice', notice['choices'][0], SOURCE, None).startswith('Remove the stock phrases') | |
| goals, keep, strength, plan = call(handlers, 'understand', 'Tighten this, leave the ending alone', SOURCE) | |
| assert 'shorten' in goals and 'ending' in keep and strength == 'light' and 'I think you want' in plan | |
| assert 'vocabulary' not in call(handlers, 'restrength', 'transformative', '', SOURCE) | |
| assert call(handlers, 'read_text', '', None)[1]['visible'] is False | |
| assert len(provider.requests) == before | |
| def test_voice_tab_builds_corrects_saves_and_forgets(studio): | |
| _, handlers, _ = studio | |
| vp, portrait, traits = call(handlers, 'on_extract', BRIDGE, 'Everyday', '', 'Everyday', '', 'Everyday', 'Never replace "I think" automatically.', True) | |
| assert 'Your Voiceprint' in portrait and 'rough' in portrait and 'confidence: low' in portrait | |
| assert 'protects: I think' in portrait and 'Download this Voiceprint' in portrait and 'rhythm' in traits['choices'] | |
| assert vp['model_read'] == 'included' and vp['unverified_dropped'] == 1 | |
| vp2, portrait2, _ = call(handlers, 'on_correction', 'formality', 'not_me', vp) | |
| assert 'you said: that isn’t me' in portrait2 | |
| vp3, portrait3, _ = call(handlers, 'on_notes', 'I hate corporate language.', vp2) | |
| assert vp3['protected_phrases'] == [] and 'I hate corporate language.' in portrait3 | |
| loaded = call(handlers, 'on_upload', json.dumps(vp3).encode()) | |
| assert loaded[0] == vp3 | |
| assert call(handlers, 'on_upload', b'{"schema_version": 1}') == tuple(gr.skip() for _ in range(3)) | |
| restored = call(handlers, 'on_load', vp3) | |
| assert restored[0] == vp3 and restored[3] is True | |
| assert call(handlers, 'on_load', {'junk': True})[0] is None and call(handlers, 'on_load', None)[3] is False | |
| assert all('Voiceprint active' in html for html in call(handlers, 'indicators', vp3)) | |
| assert call(handlers, 'on_extract', '', 'Everyday', '', 'Everyday', '', 'Everyday', '', False) == tuple(gr.skip() for _ in range(3)) | |
| *_, session = rewrite(handlers, vp=vp) | |
| assert session['versions'][0]['analysis']['voice_drift']['reference'] == 'voiceprint' | |
| assert 'I think' in session['versions'][0]['intent']['protected_phrases'] | |
| def test_cowrite_keeps_the_author_writing(studio): | |
| _, handlers, _ = studio | |
| head, options, add_button, _ = call(handlers, 'on_compose', 'The night the power went out, we', 'questions', None) | |
| assert 'Where the draft stops' in head and options['visible'] and add_button['visible'] is False | |
| _, options, add_button, _ = call(handlers, 'on_compose', 'The night the power went out, we sat still.', 'sentence', None) | |
| assert add_button['visible'] is True | |
| draft, added, mapped = call(handlers, 'on_add', 'We sat still.', options['choices'][0], []) | |
| assert draft == 'We sat still. And then the lights went out.' and added == [options['choices'][0]] | |
| assert 'AI-added' in mapped and 'p-original' in mapped | |
| edited = call(handlers, 'draft_map', 'We sat still. And then all the lights went out.', added) | |
| assert 'AI-added, then edited by you' in edited | |
| assert call(handlers, 'on_add', 'Draft.', None, []) == (gr.skip(), gr.skip(), gr.skip()) | |
| def test_amplify_offers_only_what_is_present(studio): | |
| _, handlers, _ = studio | |
| radio, absent = call(handlers, 'on_find', 'Deploy failed again. Same error. Fix it.') | |
| offered = [value for _, value in radio['choices']] | |
| assert 'directness' in offered and 'imagery' not in offered and 'imagery' in absent | |
| text, report = call(handlers, 'on_amplify', SOURCE, 'technical precision', 'light', None) | |
| assert text and 'CHANGE 01' in report and 'Where did these words come from' in report | |
| assert call(handlers, 'on_amplify', SOURCE, None, 'light', None) == (gr.skip(), gr.skip()) | |
| assert call(handlers, 'on_amplify', SOURCE, 'imagery', 'light', None) == (gr.skip(), gr.skip()) | |
| def test_demo_is_computed_live_from_two_real_calls(studio): | |
| _, handlers, provider = studio | |
| before = len(provider.requests) | |
| html = call(handlers, 'on_demo') | |
| assert len(provider.requests) == before + 2 | |
| assert provider.requests[-2].system == 'You are a helpful writing assistant.' and 'PRESERVE' in provider.requests[-1].user | |
| assert 'A conventional rewrite prompt' in html and 'HumanTouch' in html and 'produced just now' in html | |
| def test_without_a_model_generation_is_disabled_and_measurement_works(): | |
| interface = create_interface(HumanTouch(None)) | |
| buttons = {b.elem_id: b for b in interface.blocks.values() if isinstance(b, gr.Button) and b.elem_id} | |
| assert not buttons['humanize_btn'].interactive and not buttons['compose_btn'].interactive and not buttons['amplify_btn'].interactive | |
| assert buttons['extract_voice_btn'].interactive is not False | |
| handlers = {d.fn.__name__: d for d in interface.fns.values() if d.fn is not None} | |
| vp, portrait, _ = handlers['on_extract'].fn(BRIDGE, 'Everyday', '', 'Everyday', '', 'Everyday', '', True) | |
| assert vp['model_read'] == 'not requested' and 'No model was used' in portrait | |
| def test_everything_rendered_is_escaped(studio): | |
| _, handlers, _ = studio | |
| hostile = '<script>alert(1)</script> I think this could help <img src=x onerror=alert(2)>.' | |
| out = call(handlers, 'do_rewrite', hostile, '', 'light', ['grammar'], ['meaning', 'certainty'], '', '', False, None, None) | |
| for html in (out[1], out[2], out[3], out[5], out[6]): | |
| assert '<script>' not in html and '<img' not in html | |
| vp = call(handlers, 'on_extract', hostile + ' ' + BRIDGE, 'Everyday', '', 'Everyday', '', 'Everyday', '<b>bold</b> never do this', False)[0] | |
| assert '<b>bold' not in render.voiceprint(vp) and '<script>' not in render.voiceprint(vp) | |
| assert '<script>' not in render.comparison({'statements': ['<script>x</script>'], 'certainty': [], 'facts': [], 'note': 'n'}) | |