Sindhusri/codeexplainer
0
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/1vtjzZcx-6M5s7--hwieYrmSf9nEaH2jk8"""9 10 11 12#@title Code Explainer13import gradio as gr14import google.generativeai as palm15 16# load model17# PaLM API Key here18palm.configure(api_key='AIzaSyCg-5mMyeS8u9spotbRqC3c_bvP4bZM7nQ')19# Use the palm.list_models function to find available models20# PaLM 2 available in 4 sizes: Gecko, Otter, Bison and Unicorn (largest)21models = [m for m in palm.list_models() if 'generateText' in m.supported_generation_methods]22model = models[0].name23# define completion function24def get_completion(code_snippet):25 26 python_code_examples = f"""27 ---------------------28 Example 1: Code Snippet29 x = 1030 def foo():31 global x32 x = 533 foo()34 print(x)35 Correct output: 536 Code Explanation: Inside the foo function, the global keyword is used to modify the global variable x to be 5.37 So, print(x) outside the function prints the modified value, which is 5.38 ---------------------39 Example 2: Code Snippet40 def modify_list(input_list):41 input_list.append(4)42 input_list = [1, 2, 3]43 my_list = [0]44 modify_list(my_list)45 print(my_list)46 Correct output: [0, 4]47 Code Explanation: Inside the modify_list function, an element 4 is appended to input_list.48 Then, input_list is reassigned to a new list [1, 2, 3], but this change doesn't affect the original list.49 So, print(my_list) outputs [0, 4].50 ---------------------51 """52 53 prompt = f"""54 Your task is to act as any language Code Explainer.55 I'll give you a Code Snippet.56 Your job is to explain the Code Snippet step-by-step.57 Break down the code into as many steps as possible.58 Share intermediate checkpoints & steps along with results.59 Few good examples of Python code output between #### separator:60 ####61 {python_code_examples}62 ####63 Code Snippet is shared below, delimited with triple backticks:64 ```65 {code_snippet}66 ```67 """68 69 completion = palm.generate_text(70 model=model,71 prompt=prompt,72 temperature=0,73 # The maximum length of the response74 max_output_tokens=500,75 )76 response = completion.result77 return response78 79# define app UI80iface = gr.Interface(fn=get_completion, inputs=[gr.Textbox(label="Insert Code Snippet",lines=5)],81 outputs=[gr.Textbox(label="Explanation Here",lines=8)],82 title="Code Explainer"83 )84 85iface.launch()86 87 88 89 