Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,14 +1,60 @@
|
|
1 |
-
from fastapi import FastAPI
|
2 |
-
import
|
3 |
import json
|
4 |
-
import
|
|
|
|
|
|
|
|
|
|
|
5 |
|
|
|
6 |
app = FastAPI()
|
7 |
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
|
|
|
|
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
import json
|
4 |
+
import os
|
5 |
+
from datasets import Dataset, DatasetDict, DatasetInfo
|
6 |
+
from huggingface_hub import login, HfApi
|
7 |
+
from typing import List
|
8 |
+
from fastapi.responses import JSONResponse
|
9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
10 |
|
11 |
+
# Initialize FastAPI
|
12 |
app = FastAPI()
|
13 |
|
14 |
+
app.add_middleware(
|
15 |
+
CORSMiddleware,
|
16 |
+
allow_origins=["*"], # Allow all origins (or specify specific origins)
|
17 |
+
allow_credentials=True,
|
18 |
+
allow_methods=["*"], # Allow all HTTP methods
|
19 |
+
allow_headers=["*"], # Allow all headers
|
20 |
+
)
|
21 |
+
|
22 |
+
TOKEN = os.getenv("token")
|
23 |
+
|
24 |
+
|
25 |
+
class Recipe(BaseModel):
|
26 |
+
ingredients: List[str]
|
27 |
+
instructions: str
|
28 |
+
|
29 |
+
DATASET_PATH = "/mnt/data/sharktide/recipes/data"
|
30 |
+
|
31 |
+
# Ensure the 'data' folder exists
|
32 |
+
if not os.path.exists(DATASET_PATH):
|
33 |
+
os.makedirs(DATASET_PATH)
|
34 |
+
|
35 |
+
# Authentication for Hugging Face
|
36 |
+
login(token=TOKEN)
|
37 |
+
|
38 |
+
@app.put("/add/recipe")
|
39 |
+
async def add_recipe(filename: str, recipe: Recipe):
|
40 |
+
# Define the file path based on the filename query parameter
|
41 |
+
file_path = os.path.join(DATASET_PATH, f"{filename}.json")
|
42 |
|
43 |
+
# Check if the file already exists
|
44 |
+
if os.path.exists(file_path):
|
45 |
+
raise HTTPException(status_code=400, detail="File already exists")
|
46 |
|
47 |
+
# Prepare the data to be written in JSON format
|
48 |
+
recipe_data = recipe.dict() # Convert Recipe model to dictionary
|
49 |
|
50 |
+
# Write the data to the new file
|
51 |
+
try:
|
52 |
+
with open(file_path, "w") as f:
|
53 |
+
json.dump(recipe_data, f, indent=4)
|
54 |
+
|
55 |
+
dataset = Dataset.from_json(file_path) # Load the new file
|
56 |
+
dataset.push_to_hub("sharktide/recipes") # Push the dataset to the Hugging Face Hub
|
57 |
+
|
58 |
+
return {"message": f"Recipe '{filename}' added successfully."}
|
59 |
+
except Exception as e:
|
60 |
+
raise HTTPException(status_code=500, detail=f"Error writing file: {str(e)}")
|