aarunsoman commited on
Commit
0d43748
·
verified ·
1 Parent(s): 38e5a22

initial commit

Browse files
Files changed (1) hide show
  1. app.py +122 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import json
3
+ import yaml
4
+ import httpx
5
+ from transformers import pipeline
6
+ import logging
7
+
8
+ # Initialize the Hugging Face model pipeline (using text generation model for simplicity)
9
+ llm_model = pipeline('text-generation', model="bigscience/bloom-560m")
10
+
11
+ # Configure logging
12
+ logging.basicConfig(filename='api_client.log', level=logging.INFO,
13
+ format='%(asctime)s - %(levelname)s - %(message)s')
14
+
15
+
16
+ def parse_api_spec(api_spec_content):
17
+ """
18
+ This function parses the uploaded API specification and returns endpoints and their parameters.
19
+ Assumes OpenAPI format.
20
+ """
21
+ try:
22
+ # Try to load as JSON first
23
+ api_spec = json.loads(api_spec_content)
24
+ except json.JSONDecodeError:
25
+ # If it's not JSON, try loading as YAML
26
+ api_spec = yaml.safe_load(api_spec_content)
27
+
28
+ # Extract paths and methods
29
+ endpoints = {}
30
+ if 'paths' in api_spec:
31
+ for path, methods in api_spec['paths'].items():
32
+ for method, details in methods.items():
33
+ # Extract parameters
34
+ params = details.get('parameters', [])
35
+ param_info = {param['name']: param['in'] for param in params}
36
+ endpoints[f"{method.upper()} {path}"] = param_info
37
+
38
+ return endpoints
39
+
40
+ def generate_python_interface(endpoints):
41
+ """
42
+ Generates a Python interface based on the extracted API endpoints and parameters.
43
+ Includes logging of all API requests and responses.
44
+ """
45
+ interface_code = """
46
+ import httpx
47
+ import logging
48
+
49
+ # Configure logging
50
+ logging.basicConfig(filename='api_calls.log', level=logging.INFO,
51
+ format='%(asctime)s - %(levelname)s - %(message)s')
52
+
53
+ class APIClient:
54
+ def __init__(self, base_url):
55
+ self.base_url = base_url
56
+ self.client = httpx.Client()
57
+
58
+ def call_api(self, method, endpoint, params=None, json=None):
59
+ url = f"{self.base_url}{endpoint}"
60
+ logging.info(f"Requesting {method} {url} with params: {params} and body: {json}")
61
+
62
+ response = self.client.request(method, url, params=params, json=json)
63
+
64
+ logging.info(f"Received response: {response.status_code} - {response.text}")
65
+ return response.json()
66
+
67
+ # Example Usage:
68
+ # api_client = APIClient(base_url="https://api.example.com")
69
+ # response = api_client.call_api("GET", "/some-endpoint", {"param1": "value1"})
70
+ """
71
+ return interface_code
72
+
73
+ def use_llm_to_extract(api_spec):
74
+ """
75
+ Uses a Hugging Face model to extract API details.
76
+ """
77
+ prompt = f"Extract API endpoints and parameters from the following API spec:\n{api_spec}"
78
+ response = llm_model(prompt, max_length=200, num_return_sequences=1)
79
+
80
+ return response[0]['generated_text']
81
+
82
+ def main():
83
+ st.title("API Spec Uploader and Python Interface Generator")
84
+
85
+ # Upload API Spec File
86
+ uploaded_file = st.file_uploader("Upload API Spec (JSON or YAML)", type=["json", "yaml"])
87
+
88
+ if uploaded_file is not None:
89
+ api_spec_content = uploaded_file.read().decode("utf-8")
90
+
91
+ # Display API Spec
92
+ st.subheader("Uploaded API Specification")
93
+ st.code(api_spec_content, language="json" if uploaded_file.type == "application/json" else "yaml")
94
+
95
+ # Extract API endpoints and parameters using LLM
96
+ with st.spinner('Extracting API information using Hugging Face LLM...'):
97
+ extracted_info = use_llm_to_extract(api_spec_content)
98
+ st.subheader("Extracted Information from LLM")
99
+ st.write(extracted_info)
100
+
101
+ # Parse the API spec manually to display extracted endpoints
102
+ endpoints = parse_api_spec(api_spec_content)
103
+
104
+ if endpoints:
105
+ st.subheader("Parsed Endpoints and Parameters")
106
+ for endpoint, params in endpoints.items():
107
+ st.write(f"**{endpoint}**")
108
+ st.json(params)
109
+
110
+ # Generate Python interface code with logging
111
+ python_interface_code = generate_python_interface(endpoints)
112
+
113
+ st.subheader("Generated Python Interface with Logging")
114
+ st.code(python_interface_code, language="python")
115
+
116
+ st.download_button(label="Download Python Interface",
117
+ data=python_interface_code,
118
+ file_name="api_interface.py",
119
+ mime="text/plain")
120
+
121
+ if __name__ == '__main__':
122
+ main()