CoolFace
Apppublic

swagatobag/code-explainer

sourceHugging Faceupdated 2y agoView on Hugging Face
1likes
app.py76 linesDownload Raw Back to root
1import gradio as gr2import os3import google.generativeai as palm4from dotenv import load_dotenv, dotenv_values 5 6# load model7# PaLM API Key here8load_dotenv()9api_key = os.environ["HUGGING_FACE_API_KEY"]10palm.configure(api_key=api_key)11 12models = [m for m in palm.list_models() if 'generateText' in m.supported_generation_methods]13model = models[0].name14print("Using Model:", model)15 16# define the completion function17def get_completion(code_snippet):18 19  python_code_examples = f"""20  ---------------------21  Example 1: Code Snippet22  x = 1023  def foo():24      global x25      x = 526  foo()27  print(x)28  Correct output: 529  Code Explanation: Inside the foo function, the global keyword is used to modify the global variable x to be 5.30  So, print(x) outside the function prints the modified value, which is 5.31  ---------------------32  Example 2: Code Snippet33  def modify_list(input_list):34      input_list.append(4)35      input_list = [1, 2, 3]36  my_list = [0]37  modify_list(my_list)38  print(my_list)39  Correct output: [0, 4]40  Code Explanation: Inside the modify_list function, element 4 is appended to input_list.41  Then, input_list is reassigned to a new list [1, 2, 3], but this change doesn't affect the original list.42  So, print(my_list) outputs [0, 4].43  ---------------------44  """45 46  prompt = f"""47  Your task is to act as a Python Code Explainer and Reviewer.48  I'll give you a Code Snippet. Your job is to explain the Code Snippet step-by-step.49  Break down the code into as many steps as possible. Mention the DSA used inside the code. Share intermediate checkpoints & steps along with results.50  A few good examples of Python code output between #### separator:51  ####52  {python_code_examples}53  ####54  Code Snippet is shared below, delimited with triple backticks:55  ```56  {code_snippet}57  ```58  """59 60  completion = palm.generate_text(61      model=model,62      prompt=prompt,63      temperature=0.5,64      # The maximum length of the response65      max_output_tokens=1000,66      )67  response = completion.result68  return response69 70# define app UI71iface = gr.Interface(fn=get_completion, inputs=[gr.Textbox(label="Insert Code Snippet",lines=5)],72                    outputs=[gr.Textbox(label="Explanation Here",lines=5)],73                    title="Python Code Explainer"74                    )75 76iface.launch(share=True)