Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed, pipeline | |
| title = "Python to Text Converter" | |
| description = "This is a space to convert Python code into english text explaining what it does using [codeparrot-small-code-to-text](https://huggingface.co/codeparrot/codeparrot-small-code-to-text),\ | |
| a code generation model for Python finetuned on [github-jupyter-code-to-text](https://huggingface.co/datasets/codeparrot/github-jupyter-code-to-text) a dataset of Python code followed by a docstring explaining it, the data was originally extracted from Jupyter notebooks." | |
| EXAMPLE_1 = "def bubblesort(elements):\n n = len(arr)\n# loop through elements\n swapped = False\n for n in range(len(elements)-1, 0, -1):\n for i in range(n):\n if elements[i] > elements[i + 1]:\n swapped = True\n elements[i], elements[i + 1] = elements[i + 1], elements[i]\n if not swapped:\n return" | |
| EXAMPLE_2 = "from sklearn.linear_model import LogisticRegression\n\n#split the dataset\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=0.2)\n# Fit the model on training set\nmodel = LogisticRegression()\nmodel.fit(X_train, Y_train)" | |
| example = [ | |
| [EXAMPLE_1, 60, 0.6, 42], | |
| [EXAMPLE_2, 60, 0.6, 42], | |
| ] | |
| # change model to the finetuned one | |
| tokenizer = AutoTokenizer.from_pretrained("codeparrot/codeparrot-small-code-to-text") | |
| model = AutoModelForCausalLM.from_pretrained("codeparrot/codeparrot-small-code-to-text") | |
| def make_doctring(gen_prompt): | |
| return gen_prompt + f"\n\n\"\"\"\nExplanation:" | |
| def code_generation(gen_prompt, max_tokens, temperature=0.6, seed=42): | |
| set_seed(seed) | |
| pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) | |
| prompt = make_doctring(gen_prompt) | |
| generated_text = pipe(prompt, do_sample=True, top_p=0.95, temperature=temperature, max_new_tokens=max_tokens)[0]['generated_text'] | |
| return generated_text | |
| iface = gr.Interface( | |
| fn=code_generation, | |
| inputs=[ | |
| gr.Textbox(lines=10, label="Python code"), | |
| gr.inputs.Slider( | |
| minimum=8, | |
| maximum=256, | |
| step=1, | |
| default=8, | |
| label="Number of tokens to generate", | |
| ), | |
| gr.inputs.Slider( | |
| minimum=0, | |
| maximum=2.5, | |
| step=0.1, | |
| default=0.6, | |
| label="Temperature", | |
| ), | |
| gr.inputs.Slider( | |
| minimum=0, | |
| maximum=1000, | |
| step=1, | |
| default=42, | |
| label="Random seed to use for the generation" | |
| ) | |
| ], | |
| outputs=gr.Textbox(label="Predicted explanation", lines=10), | |
| examples=example, | |
| layout="horizontal", | |
| theme="peach", | |
| description=description, | |
| title=title | |
| ) | |
| iface.launch() | |