Team Ai
Apppublic

Akshaya03/codeExplainer

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py91 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/1AmObCmT1FemiXYJt-B9uktBavVDnrah98"""9 10 11 12#@title Code Explainer13import gradio as gr14import os15import google.generativeai as palm16 17# load model18# PaLM API Key here19palm.configure(api_key='AIzaSyBPWGWsGxFv8D0sQsmMXenhaTqnADKV1GQ')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 25# define completion function26def get_completion(code_snippet):27 28  python_code_examples = f"""29  ---------------------30  Example 1: Code Snippet31  x = 1032  def foo():33      global x34      x = 535  foo()36  print(x)37  Correct output: 538  Code Explanation: Inside the foo function, the global keyword is used to modify the global variable x to be 5.39  So, print(x) outside the function prints the modified value, which is 5.40  ---------------------41  Example 2: Code Snippet42  def modify_list(input_list):43      input_list.append(4)44      input_list = [1, 2, 3]45  my_list = [0]46  modify_list(my_list)47  print(my_list)48  Correct output: [0, 4]49  Code Explanation: Inside the modify_list function, an element 4 is appended to input_list.50  Then, input_list is reassigned to a new list [1, 2, 3], but this change doesn't affect the original list.51  So, print(my_list) outputs [0, 4].52  ---------------------53  """54 55  prompt = f"""56  Your task is to act as any language Code Explainer.57  I'll give you a Code Snippet.58  Your job is to explain the Code Snippet step-by-step.59  Break down the code into as many steps as possible.60  Share intermediate checkpoints & steps along with results.61  Few good examples of Python code output between #### separator:62  ####63  {python_code_examples}64  ####65  Code Snippet is shared below, delimited with triple backticks:66  ```67  {code_snippet}68  ```69  """70 71  completion = palm.generate_text(72      model=model,73      prompt=prompt,74      temperature=0,75      # The maximum length of the response76      max_output_tokens=500,77      )78  response = completion.result79  return response80 81# define app UI82iface = gr.Interface(fn=get_completion, inputs=[gr.Textbox(label="Insert Code Snippet",lines=5)],83                    outputs=[gr.Textbox(label="Explanation Here",lines=8)],84                    title="Code Explainer"85                    )86 87iface.launch()88 89 90 91