ysharma/function-to-JSON
6
1import inspect2import json3import ast4import gradio as gr5 6 7def function_to_json(func_str, func_description, param_descriptions, required_params):8 # Create a new Module instance with the missing field9 module_ast = ast.Module(body=[ast.Pass()], type_ignores=[])10 11 # Parse the function string into the AST and replace the body12 func_ast = ast.parse(func_str)13 module_ast.body = func_ast.body14 15 # Extract the function definition node16 func_def = next(node for node in module_ast.body if isinstance(node, ast.FunctionDef))17 18 # Get function signature19 code_obj = compile(module_ast, '<string>', 'exec')20 func_globals = {}21 exec(code_obj, func_globals)22 signature = inspect.signature(func_globals[func_def.name])23 parameters = signature.parameters24 25 # Convert param_descriptions string to a dictionary26 param_desc_dict = json.loads(param_descriptions)27 28 # Create JSON structure29 function_json = {30 "name": func_def.name,31 "description": func_description,32 "parameters": {33 "type": "object",34 "properties": {}35 }36 }37 38 # Add parameter information to JSON structure39 for param_name, param in parameters.items():40 param_info = param_desc_dict.get(param_name, {})41 param_type = param_info.get("type", str(param.annotation))42 param_desc = param_info.get("description", param_name.replace('_', ' '))43 44 function_json["parameters"]["properties"][param_name] = {45 "type": param_type,46 "description": param_desc47 }48 49 # Add required parameters based on user input50 if param_name in required_params:51 if "required" not in function_json["parameters"]:52 function_json["parameters"]["required"] = []53 function_json["parameters"]["required"].append(param_name)54 55 return json.dumps(function_json, indent=4)56 57 58""" Example uasge:59# Example usage with user-provided function information60sample_function_str = '''61def generate_music(input_text, input_melody):62 ''' generate music based on an input text '''63 client = Client("https://ysharma-musicgendupe.hf.space/", hf_token="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")64 result = client.predict(65 "melody",66 input_text,67 input_melody,68 5,69 250,70 0,71 1,72 3,73 fn_index=174 )75 return result76'''77 78sample_func_description = "generate music based on an input text and input melody"79 80sample_param_descriptions = '''81{82 "input_text": {83 "type": "str",84 "description": "Input text for music generation."85 },86 "input_melody": {87 "type": "str",88 "description": "File path of the input melody."89 }90}91'''92 93sample_required_params = ["input_text"]94 95# Convert the sample function information to JSON96json_str = function_to_json(sample_function_str, sample_func_description, sample_param_descriptions, sample_required_params)97print(json_str)98 99{100 "name": "generate_music",101 "description": "generate music based on an input text and input melody",102 "parameters": {103 "type": "object",104 "properties": {105 "input_text": {106 "type": "str",107 "description": "Input text for music generation."108 },109 "input_melody": {110 "type": "str",111 "description": "File path of the input melody."112 }113 },114 "required": [115 "input_text"116 ]117 }118}119 120"""121 122 123title = "<h1 align='center'>Convert any function to function definitions required for GPT</h1>"124demo = gr.Blocks()125 126with demo:127 gr.HTML(title)128 with gr.Row():129 input_function_str = gr.Code(label="Enter function definition", language='python', lines=10)130 #input_function_str = gr.Textbox(lines=10, label='Enter function definition')131 with gr.Column():132 input_func_description = gr.Textbox(placeholder='', label='Enter your function description:')133 input_param_description = gr.Textbox(134 placeholder="""Enter description as a dictionary with keys as param_name and values as param type and description as shown, eg. -135 {136 "param1": {137 "type": "str",138 "description": "description of param1"139 },140 "param2": {141 "type": "int/float/list/tuple/dict/set/bool etc..",142 "description": "description of param2"143 }144 }""",145 label='Enter descriptions for parameters:')146 input_required_params = gr.Textbox(placeholder="""Enter a list of required parameters, eg. - ['param1', 'param2', ...]""",147 label='Enter required parameters for your function:')148 generate_json = gr.Button('Get JSON definition')149 gpt_function = gr.Code(label="GPT function definition", language='python', lines=7)150 151 generate_json.click(function_to_json,152 [input_function_str, input_func_description, input_param_description, input_required_params],153 [gpt_function])154 155 gr.Examples(156 [ ["""157 def generate_music(input_text, input_melody):158 "generate music based on an input text"159 client = Client("https://ysharma-musicgendupe.hf.space/", hf_token="hf_...")160 result = client.predict(161 "melody",162 input_text,163 input_melody,164 5,165 250,166 0,167 1,168 3,169 fn_index=1170 )171 return result172 """,173 """Generate music based on an input text.""",174 """{175 "input_text": {176 "type": "string",177 "description": "Input text for music generation."178 },179 "input_melody": {180 "type": "string",181 "description": "File path of the input melody."182 }183 }""",184 """["input_text"]""" ],185 186 ["""187 def generate_image(prompt):188 client = Client("https://jingyechen22-textdiffuser.hf.space/")189 result = client.predict(190 prompt,191 20,192 7.5,193 1,194 "Stable Diffusion v2.1",195 fn_index=1)196 return result[0]197 """,198 """generate image based on the input text prompt""",199 """{200 "prompt": {201 "type": "string",202 "description": "input text prompt for the image generation."203 }204 }""",205 """["prompt"]""" ,206 ],207 ],208 [input_function_str, input_func_description, input_param_description, input_required_params],209 )210 demo.launch() #(debug=True)211 212 