CoolFace
Apppublic

rahuulupadhyay/CodeExplainer

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py90 linesDownload Raw Back to root
1# -*- coding: utf-8 -*-2"""Copy of Code Explainer.ipynb3 4Automatically generated by Colaboratory.5 6Original file is located at7    https://colab.research.google.com/drive/1c0ymczLYGTrThSO8jNJ5UDvfB-7PW76h8"""9 10'''!pip install gradio11!pip install google-generativeai'''12 13#@title Code Explainer14import gradio as gr15import google.generativeai as palm16 17# load model18# PaLM API Key here19palm.configure(api_key='AIzaSyA8bVYUoQX-CYOWO1VLNy8VeoxnVf9wlsg')20# Use the palm.list_models function to find available models21# PaLM 2 available in 4 sizes: Gecko, Otter, Bison and Unicorn (largest)22models = [m for m in palm.list_models() if 'generateText' in m.supported_generation_methods]23model = models[0].name24# define completion function25def get_completion(code_snippet):26 27  python_code_examples = f"""28  ---------------------29  Example 1: Code Snippet30  x = 1031  def foo():32      global x33      x = 534  foo()35  print(x)36  Correct output: 537  Code Explanation: Inside the foo function, the global keyword is used to modify the global variable x to be 5.38  So, print(x) outside the function prints the modified value, which is 5.39  ---------------------40  Example 2: Code Snippet41  def modify_list(input_list):42      input_list.append(4)43      input_list = [1, 2, 3]44  my_list = [0]45  modify_list(my_list)46  print(my_list)47  Correct output: [0, 4]48  Code Explanation: Inside the modify_list function, an element 4 is appended to input_list.49  Then, input_list is reassigned to a new list [1, 2, 3], but this change doesn't affect the original list.50  So, print(my_list) outputs [0, 4].51  ---------------------52  """53 54  prompt = f"""55  Your task is to act as any language Code Explainer.56  I'll give you a Code Snippet.57  Your job is to explain the Code Snippet step-by-step.58  Break down the code into as many steps as possible.59  Share intermediate checkpoints & steps along with results.60  Few good examples of Python code output between #### separator:61  ####62  {python_code_examples}63  ####64  Code Snippet is shared below, delimited with triple backticks:65  ```66  {code_snippet}67  ```68  """69 70  completion = palm.generate_text(71      model=model,72      prompt=prompt,73      temperature=0,74      # The maximum length of the response75      max_output_tokens=500,76      )77  response = completion.result78  return response79 80# define app UI81iface = gr.Interface(fn=get_completion, inputs=[gr.Textbox(label="Insert Code Snippet",lines=5)],82                    outputs=[gr.Textbox(label="Explanation Here",lines=8)],83                    title="Code Explainer"84                    )85 86iface.launch()87 88 89 90