binaychandra commited on
Commit
db8243f
·
0 Parent(s):

App first version

Browse files
Files changed (4) hide show
  1. Dockerfile +16 -0
  2. README.md +12 -0
  3. app.py +119 -0
  4. requirements.txt +3 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
+ # you will also find guides on how best to write your Dockerfile
3
+
4
+ FROM python:3.9
5
+
6
+ RUN useradd -m -u 1000 user
7
+ USER user
8
+ ENV PATH="/home/user/.local/bin:$PATH"
9
+
10
+ WORKDIR /app
11
+
12
+ COPY --chown=user ./requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
+
15
+ COPY --chown=user . /app
16
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Fastapi First
3
+ emoji: 🌍
4
+ colorFrom: purple
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ short_description: A space for fastapi endpoint
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ import os
3
+ import requests
4
+ import json
5
+ import time
6
+ from datetime import datetime
7
+ from fastapi import FastAPI
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+
10
+ app = FastAPI()
11
+
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():
26
+ return {"Hello": "World"}
27
+
28
+ @app.get("/get_prediction")
29
+ def get_prediction_from_jobrun():
30
+ #Add the documentation
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}',
42
+ 'Content-Type': 'application/json'
43
+ }
44
+ data = {
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:
52
+ print("Pipeline run initiated successfully.")
53
+ output_json = json.loads(response.json()['notebook_output']['result'])
54
+ nb_output = output_json['prediction']
55
+ return nb_output
56
+ else:
57
+ print(response)
58
+ print("Failed to initiate pipeline run.")
59
+ print("Status Code:", response.status_code)
60
+ return response.text
61
+
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': {
83
+ 'data': json_data # Send data as a JSON string
84
+ }
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")
92
+ run_id = response_json["run_id"]
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']
100
+ run_status = response_json["state"]["life_cycle_state"]
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
+
117
+ @app.get("/items/{item_id}")
118
+ def read_item(item_id: int, q: Union[str, None] = None):
119
+ return {"item_id": item_id, "q": q}
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ fastapi
2
+ requests
3
+ uvicorn[standard]