Team Ai
Apppublic

mamiksik/commit-message-generator

sourceHugging Faceupdated 4y agoView on Hugging Face
11likes
app.py214 linesDownload Raw Back to root
1import re2 3import gradio as gr4import torch5from transformers import T5ForConditionalGeneration, RobertaTokenizer6 7 8tokenizer = RobertaTokenizer.from_pretrained("mamiksik/CommitPredictorT5PL", revision="fb08d01")9model = T5ForConditionalGeneration.from_pretrained("mamiksik/CommitPredictorT5PL", revision="fb08d01")10 11 12def parse_files(patch):13    accumulator = []14    lines = patch.splitlines()15 16    filename_before = None17    for line in lines:18        if line.startswith("index") or line.startswith("diff"):19            continue20        if line.startswith("---"):21            filename_before = line.split(" ", 1)[1][1:]22            continue23 24        if line.startswith("+++"):25            filename_after = line.split(" ", 1)[1][1:]26 27            if filename_before == filename_after:28                accumulator.append(f"<ide><path>{filename_before}")29            else:30                accumulator.append(f"<add><path>{filename_after}")31                accumulator.append(f"<del><path>{filename_before}")32            continue33 34        line = re.sub("@@[^@@]*@@", "", line)35        if len(line) == 0:36            continue37 38        if line[0] == "+":39            line = line.replace("+", "<add>", 1)40        elif line[0] == "-":41            line = line.replace("-", "<del>", 1)42        else:43            line = f"<ide>{line}"44 45        accumulator.append(line)46 47    return '\n'.join(accumulator)48 49 50def predict(patch, max_length, min_length, num_beams, prediction_count):51    input_text = parse_files(patch)52    with torch.no_grad():53        token_count = tokenizer(input_text, return_tensors="pt").input_ids.shape[1]54 55        input_ids = tokenizer(56            input_text,57            truncation=True,58            padding=True,59            return_tensors="pt",60        ).input_ids61 62        outputs = model.generate(63            input_ids,64            max_length=max_length,65            min_length=min_length,66            num_beams=num_beams,67            num_return_sequences=prediction_count,68        )69 70    result = tokenizer.batch_decode(outputs, skip_special_tokens=True)71    return token_count, input_text, {k: 0 for k in result}72 73 74iface = gr.Interface(fn=predict, inputs=[75    gr.Textbox(label="Patch (as generated by git diff)"),76    gr.Slider(1, 128, value=40, label="Max message length"),77    gr.Slider(1, 128, value=5, label="Min message length"),78    gr.Slider(1, 10, value=7, label="Number of beams"),79    gr.Slider(1, 15, value=5, label="Number of predictions"),80], outputs=[81    gr.Textbox(label="Token count"),82    gr.Textbox(label="Parsed patch"),83    gr.Label(label="Predictions")84], examples=[85["""86diff --git a/.github/workflows/pylint.yml b/.github/workflows/codestyle_checks.yml87similarity index 86%88rename from .github/workflows/pylint.yml89rename to .github/workflows/codestyle_checks.yml90index a5d5c4d9..8cbf9713 10064491--- a/.github/workflows/pylint.yml92+++ b/.github/workflows/codestyle_checks.yml93@@ -20,3 +20,6 @@ jobs:94     - name: Analysing the code with pylint95       run: |96         pylint --rcfile=.pylintrc webapp core97+    - name: Analysing the code with flake898+      run: |99+        flake8100""", 40, 5, 7, 5],101["""102diff --git a/packages/react-native-renderer/src/ReactFabricHostConfig.js b/packages/react-native-renderer/src/ReactFabricHostConfig.js103index 078bf1f11ac6..b6d370882ae4 100644104--- a/packages/react-native-renderer/src/ReactFabricHostConfig.js105+++ b/packages/react-native-renderer/src/ReactFabricHostConfig.js106@@ -18,7 +18,10 @@ import type {107   TouchedViewDataAtPoint,108 } from './ReactNativeTypes';109 110-import {mountSafeCallback_NOT_REALLY_SAFE} from './NativeMethodsMixinUtils';111+import {112+  mountSafeCallback_NOT_REALLY_SAFE,113+  warnForStyleProps,114+} from './NativeMethodsMixinUtils';115 import {create, diff} from './ReactNativeAttributePayload';116 117 import {dispatchEvent} from './ReactFabricEventEmitter';118@@ -52,6 +55,7 @@ const {119   unstable_DefaultEventPriority: FabricDefaultPriority,120   unstable_DiscreteEventPriority: FabricDiscretePriority,121   unstable_getCurrentEventPriority: fabricGetCurrentEventPriority,122+  setNativeProps,123 } = nativeFabricUIManager;124 125 const {get: getViewConfigForType} = ReactNativeViewConfigRegistry;126@@ -208,12 +212,14 @@ class ReactFabricHostComponent {127 128   setNativeProps(nativeProps: Object) {129     if (__DEV__) {130-      console.error(131-        'Warning: setNativeProps is not currently supported in Fabric',132-      );133+      warnForStyleProps(nativeProps, this.viewConfig.validAttributes);134     }135+    const updatePayload = create(nativeProps, this.viewConfig.validAttributes);136 137-    return;138+    const {stateNode} = this._internalInstanceHandle;139+    if (stateNode != null && updatePayload != null) {140+      setNativeProps(stateNode.node, updatePayload);141+    }142   }143 144   // This API (addEventListener, removeEventListener) attempts to adhere to the145diff --git a/packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager.js b/packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager.js146index abb2883d387e..ab4fc291d6d6 100644147--- a/packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager.js148+++ b/packages/react-native-renderer/src/__mocks__/react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager.js149@@ -117,6 +117,8 @@ const RCTFabricUIManager = {150 151   dispatchCommand: jest.fn(),152 153+  setNativeProps: jest.fn(),154+155   sendAccessibilityEvent: jest.fn(),156 157   registerEventHandler: jest.fn(function registerEventHandler(callback) {}),158diff --git a/packages/react-native-renderer/src/__tests__/ReactFabricHostComponent-test.internal.js b/packages/react-native-renderer/src/__tests__/ReactFabricHostComponent-test.internal.js159index 337a4976bbe8..51e056d1c8bc 100644160--- a/packages/react-native-renderer/src/__tests__/ReactFabricHostComponent-test.internal.js161+++ b/packages/react-native-renderer/src/__tests__/ReactFabricHostComponent-test.internal.js162@@ -38,7 +38,7 @@ function mockRenderKeys(keyLists) {163 164   const mockContainerTag = 11;165   const MockView = createReactNativeComponentClass('RCTMockView', () => ({166-    validAttributes: {},167+    validAttributes: {foo: true},168     uiViewClassName: 'RCTMockView',169   }));170 171@@ -200,21 +200,15 @@ describe('measureLayout', () => {172 });173 174 describe('setNativeProps', () => {175-  test('setNativeProps(...) emits a warning', () => {176+  test('setNativeProps(...) invokes setNativeProps on Fabric UIManager', () => {177     const {178       UIManager,179     } = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface');180 181     const [[fooRef]] = mockRenderKeys([['foo']]);182+    fooRef.setNativeProps({foo: 'baz'});183 184-    expect(() => {185-      fooRef.setNativeProps({});186-    }).toErrorDev(187-      ['Warning: setNativeProps is not currently supported in Fabric'],188-      {189-        withoutStack: true,190-      },191-    );192     expect(UIManager.updateView).not.toBeCalled();193+    expect(nativeFabricUIManager.setNativeProps).toHaveBeenCalledTimes(1);194   });195 });196diff --git a/scripts/flow/react-native-host-hooks.js b/scripts/flow/react-native-host-hooks.js197index 584f24ee084c..e3c98114935f 100644198--- a/scripts/flow/react-native-host-hooks.js199+++ b/scripts/flow/react-native-host-hooks.js200@@ -186,7 +186,7 @@ declare var nativeFabricUIManager: {201       payload: Object,202     ) => void,203   ) => void,204-205+  setNativeProps: (node: Object, nativeProps: Object) => Object,206   dispatchCommand: (node: Object, command: string, args: Array<any>) => void,207   sendAccessibilityEvent: (node: Object, eventTypeName: string) => void,208""", 40, 5, 7, 5]209]210)211 212if __name__ == "__main__":213    iface.launch()214