binaychandra commited on
Commit
82b91c3
·
1 Parent(s): db8243f

API related changes

Browse files
Files changed (1) hide show
  1. app.py +15 -27
app.py CHANGED
@@ -12,14 +12,19 @@ app = FastAPI()
12
  # Configure CORS settings
13
  app.add_middleware(
14
  CORSMiddleware,
15
- allow_origins=["https://react-first-tan.vercel.app/"], # List of allowed origins
16
  allow_credentials=True,
17
  allow_methods=["*"], # Allow all HTTP methods
18
  allow_headers=["*"], # Allow all headers
19
  )
20
 
21
- from dotenv import load_dotenv, find_dotenv
22
- _ = load_dotenv(find_dotenv()) # read local .env file
 
 
 
 
 
23
 
24
  @app.get("/")
25
  def read_root():
@@ -31,11 +36,6 @@ def get_prediction_from_jobrun():
31
  """
32
  Get the prediction from the Databricks job run
33
  """
34
- # Replace these variables with your Databricks workspace information
35
- DATABRICKS_INSTANCE = 'https://2461626258595269.9.gcp.databricks.com'
36
- API_TOKEN = os.getenv('API_TOKEN')
37
- TASK_RUNID = '1054089068841244'
38
-
39
  url = f"{DATABRICKS_INSTANCE}/api/2.1/jobs/runs/get-output"
40
  headers = {
41
  'Authorization': f'Bearer {API_TOKEN}',
@@ -45,7 +45,6 @@ def get_prediction_from_jobrun():
45
  "run_id": TASK_RUNID
46
  }
47
 
48
- #cert_path = r"C:\Users\PD817AE\OneDrive - EY\Desktop\mdlz\pipeline_code\Zscaler Root CA.crt"
49
  response = requests.get(url, headers=headers, data=json.dumps(data))
50
 
51
  if response.status_code == 200:
@@ -62,21 +61,14 @@ def get_prediction_from_jobrun():
62
  @app.get("/get_prediction_from_databricks")
63
  def run_xpipeline():
64
  print(f"Running the pipeline : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ")
65
- access_token_dev = os.getenv('API_TOKEN')
66
  headers = {
67
- "Authorization": f"Bearer {access_token_dev}",
68
  "Content-Type": "application/json"
69
  }
70
  # Pipeline details
71
-
72
- pipeline_id = "413640122908266" # "326843486210150"
73
- #sample_df = pd.read_csv("wine_test_dataset.csv")
74
- #print(f"============= Input Data ============")
75
- #print(sample_df)
76
- #print(f"=====================================")
77
-
78
- # Convert the DataFrame to JSON
79
- json_data = None #sample_df.to_json()
80
  payload = {
81
  'job_id': pipeline_id,
82
  'notebook_params': {
@@ -85,7 +77,7 @@ def run_xpipeline():
85
  }
86
 
87
  # Trigger the run
88
- api_url = f"https://2461626258595269.9.gcp.databricks.com/api/2.1/jobs/run-now"
89
  response = requests.post(api_url, headers=headers, data=json.dumps(payload))
90
  response_json = response.json()
91
  print(f"\nPrediction pipeline started with details : {response_json}\n")
@@ -93,7 +85,7 @@ def run_xpipeline():
93
  #pred_out = pd.DataFrame()
94
  while True:
95
  time.sleep(2)
96
- api_url = f"https://2461626258595269.9.gcp.databricks.com/api/2.1/jobs/runs/get?run_id={run_id}"
97
  response = requests.get(api_url, headers=headers)
98
  response_json = response.json()
99
  task_run_id = response_json['tasks'][0]['run_id']
@@ -101,16 +93,12 @@ def run_xpipeline():
101
  print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Status : {run_status}")
102
  job_status = response_json["state"].get('result_state')
103
  if job_status == 'SUCCESS':
104
- api_url = f"https://2461626258595269.9.gcp.databricks.com/api/2.1/jobs/runs/get-output"
105
  payload = dict(run_id=task_run_id)
106
  response = requests.get(api_url, headers=headers, data=json.dumps(payload))
107
- #response_dict = response.json()
108
  output_json = json.loads(response.json()['notebook_output']['result'])
109
  nb_output = output_json['prediction']
110
- #notebook_output = json.loads(response_dict["notebook_output"]["result"])
111
  break;
112
- #pred_out = pd.DataFrame(notebook_output)
113
- #break
114
 
115
  return nb_output
116
 
 
12
  # Configure CORS settings
13
  app.add_middleware(
14
  CORSMiddleware,
15
+ allow_origins=["https://npd-studio.vercel.app/"], # List of allowed origins
16
  allow_credentials=True,
17
  allow_methods=["*"], # Allow all HTTP methods
18
  allow_headers=["*"], # Allow all headers
19
  )
20
 
21
+ # Replace these variables with your Databricks workspace information
22
+ DATABRICKS_INSTANCE = os.getenv('DATABRICKS_INSTANCE')
23
+ API_TOKEN = os.getenv('API_TOKEN')
24
+ TASK_RUNID = "1054089068841244"
25
+
26
+ # from dotenv import load_dotenv, find_dotenv
27
+ # _ = load_dotenv(find_dotenv()) # read local .env file
28
 
29
  @app.get("/")
30
  def read_root():
 
36
  """
37
  Get the prediction from the Databricks job run
38
  """
 
 
 
 
 
39
  url = f"{DATABRICKS_INSTANCE}/api/2.1/jobs/runs/get-output"
40
  headers = {
41
  'Authorization': f'Bearer {API_TOKEN}',
 
45
  "run_id": TASK_RUNID
46
  }
47
 
 
48
  response = requests.get(url, headers=headers, data=json.dumps(data))
49
 
50
  if response.status_code == 200:
 
61
  @app.get("/get_prediction_from_databricks")
62
  def run_xpipeline():
63
  print(f"Running the pipeline : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ")
64
+
65
  headers = {
66
+ "Authorization": f"Bearer {API_TOKEN}",
67
  "Content-Type": "application/json"
68
  }
69
  # Pipeline details
70
+ pipeline_id = "413640122908266"
71
+ json_data = None
 
 
 
 
 
 
 
72
  payload = {
73
  'job_id': pipeline_id,
74
  'notebook_params': {
 
77
  }
78
 
79
  # Trigger the run
80
+ api_url = f"{DATABRICKS_INSTANCE}/api/2.1/jobs/run-now"
81
  response = requests.post(api_url, headers=headers, data=json.dumps(payload))
82
  response_json = response.json()
83
  print(f"\nPrediction pipeline started with details : {response_json}\n")
 
85
  #pred_out = pd.DataFrame()
86
  while True:
87
  time.sleep(2)
88
+ api_url = f"{DATABRICKS_INSTANCE}/api/2.1/jobs/runs/get?run_id={run_id}"
89
  response = requests.get(api_url, headers=headers)
90
  response_json = response.json()
91
  task_run_id = response_json['tasks'][0]['run_id']
 
93
  print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Status : {run_status}")
94
  job_status = response_json["state"].get('result_state')
95
  if job_status == 'SUCCESS':
96
+ api_url = f"{DATABRICKS_INSTANCE}/api/2.1/jobs/runs/get-output"
97
  payload = dict(run_id=task_run_id)
98
  response = requests.get(api_url, headers=headers, data=json.dumps(payload))
 
99
  output_json = json.loads(response.json()['notebook_output']['result'])
100
  nb_output = output_json['prediction']
 
101
  break;
 
 
102
 
103
  return nb_output
104