Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,13 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
-
from
|
| 6 |
-
from
|
| 7 |
from typing import List
|
| 8 |
-
from
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 10 |
|
| 11 |
-
# Initialize FastAPI
|
| 12 |
app = FastAPI()
|
| 13 |
|
| 14 |
app.add_middleware(
|
|
@@ -19,66 +18,54 @@ app.add_middleware(
|
|
| 19 |
allow_headers=["*"], # Allow all headers
|
| 20 |
)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
TOKEN = os.getenv("token")
|
| 24 |
-
|
| 25 |
-
# Ensure the token is available
|
| 26 |
if not TOKEN:
|
| 27 |
-
raise ValueError("
|
| 28 |
|
| 29 |
-
#
|
| 30 |
login(token=TOKEN)
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
|
|
|
| 37 |
|
|
|
|
| 38 |
class Recipe(BaseModel):
|
| 39 |
ingredients: List[str]
|
| 40 |
instructions: str
|
| 41 |
|
| 42 |
-
# Function to load the existing dataset or create a new one
|
| 43 |
-
def load_or_create_dataset():
|
| 44 |
-
dataset_files = [f for f in os.listdir(DATASET_PATH) if f.endswith(".json")]
|
| 45 |
-
all_recipes = []
|
| 46 |
-
|
| 47 |
-
for file_name in dataset_files:
|
| 48 |
-
file_path = os.path.join(DATASET_PATH, file_name)
|
| 49 |
-
with open(file_path, "r") as f:
|
| 50 |
-
recipe_data = json.load(f)
|
| 51 |
-
all_recipes.append(recipe_data)
|
| 52 |
-
|
| 53 |
-
return Dataset.from_dict({"data": all_recipes}) if all_recipes else None
|
| 54 |
-
|
| 55 |
@app.put("/add/recipe")
|
| 56 |
async def add_recipe(filename: str, recipe: Recipe):
|
| 57 |
-
# Define the file path
|
| 58 |
-
file_path = os.path.join(
|
| 59 |
-
|
| 60 |
-
#
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
#
|
| 65 |
-
recipe_data = recipe.dict() # Convert Recipe model to dictionary
|
| 66 |
-
|
| 67 |
-
# Write the data to the new file as JSON
|
| 68 |
try:
|
| 69 |
-
with open(file_path, "
|
| 70 |
-
json.dump(recipe_data, f
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
dataset
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
dataset.
|
| 81 |
-
|
| 82 |
-
return {"message": f"Recipe '{filename}' added successfully."}
|
| 83 |
except Exception as e:
|
| 84 |
raise HTTPException(status_code=500, detail=f"Error writing file: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import os
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
from typing import List
|
| 6 |
+
from huggingface_hub import login, HfApi
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
+
from datetime import datetime
|
| 9 |
|
| 10 |
+
# Initialize FastAPI app
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
app.add_middleware(
|
|
|
|
| 18 |
allow_headers=["*"], # Allow all headers
|
| 19 |
)
|
| 20 |
|
| 21 |
+
# Token for Hugging Face (using the token environment variable as 'token')
|
| 22 |
+
TOKEN = os.getenv("token")
|
|
|
|
|
|
|
| 23 |
if not TOKEN:
|
| 24 |
+
raise ValueError("The 'token' environment variable is missing.")
|
| 25 |
|
| 26 |
+
# Authenticate with Hugging Face Hub
|
| 27 |
login(token=TOKEN)
|
| 28 |
|
| 29 |
+
# Hugging Face API for dataset handling
|
| 30 |
+
hf_api = HfApi()
|
| 31 |
+
|
| 32 |
+
# Define the folder for storing the dataset locally
|
| 33 |
+
JSON_DATASET_DIR = "json_dataset"
|
| 34 |
+
os.makedirs(JSON_DATASET_DIR, exist_ok=True)
|
| 35 |
|
| 36 |
+
# Dataset info (to be used when pushing to Hugging Face Hub)
|
| 37 |
+
dataset_repo = "sharktide/recipes" # Change to your repo name on Hugging Face Hub
|
| 38 |
+
DATASET_PATH = os.path.join(JSON_DATASET_DIR, "data")
|
| 39 |
|
| 40 |
+
# Define the Recipe model
|
| 41 |
class Recipe(BaseModel):
|
| 42 |
ingredients: List[str]
|
| 43 |
instructions: str
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
@app.put("/add/recipe")
|
| 46 |
async def add_recipe(filename: str, recipe: Recipe):
|
| 47 |
+
# Define the file path for saving the recipe in JSON format
|
| 48 |
+
file_path = os.path.join(JSON_DATASET_DIR, f"{filename}.json")
|
| 49 |
+
|
| 50 |
+
# Prepare the data to be saved
|
| 51 |
+
recipe_data = recipe.dict()
|
| 52 |
+
recipe_data["datetime"] = datetime.now().isoformat() # Add timestamp to the entry
|
| 53 |
+
|
| 54 |
+
# Save the recipe to the JSON file
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
+
with open(file_path, "a") as f:
|
| 57 |
+
json.dump(recipe_data, f)
|
| 58 |
+
f.write("\n") # Add a newline after each entry
|
| 59 |
+
|
| 60 |
+
# Push the updated data directly to the Hugging Face dataset repo
|
| 61 |
+
hf_api.dataset_push_to_hub(
|
| 62 |
+
repo_id=dataset_repo,
|
| 63 |
+
path_in_repo="data",
|
| 64 |
+
folder_path=JSON_DATASET_DIR
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
return {"message": f"Recipe '{filename}' added and pushed to Hugging Face dataset."}
|
| 68 |
+
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
raise HTTPException(status_code=500, detail=f"Error writing file: {str(e)}")
|
| 71 |
+
|