sharktide commited on
Commit
9bb0e82
·
verified ·
1 Parent(s): eb1102e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -54
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 datasets import Dataset, DatasetDict
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(
@@ -19,66 +18,54 @@ app.add_middleware(
19
  allow_headers=["*"], # Allow all headers
20
  )
21
 
22
- # Get Hugging Face token from environment variable
23
- TOKEN = os.getenv("token") # Make sure to set HF_TOKEN environment variable
24
-
25
- # Ensure the token is available
26
  if not TOKEN:
27
- raise ValueError("HF_TOKEN environment variable is missing.")
28
 
29
- # Authentication for Hugging Face
30
  login(token=TOKEN)
31
 
32
- # Define the data folder and recipe model
33
- DATASET_PATH = "/app/data"
 
 
 
 
34
 
35
- if not os.path.exists(DATASET_PATH):
36
- os.makedirs(DATASET_PATH)
 
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 based on the filename query parameter
58
- file_path = os.path.join(DATASET_PATH, f"{filename}.json")
59
-
60
- # Check if the file already exists
61
- if os.path.exists(file_path):
62
- raise HTTPException(status_code=400, detail="File already exists")
63
-
64
- # Prepare the data to be written in JSON format
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, "w") as f:
70
- json.dump(recipe_data, f, indent=4)
71
-
72
- # Load the updated dataset
73
- dataset = load_or_create_dataset()
74
-
75
- # If dataset does not exist, initialize a new one
76
- if not dataset:
77
- dataset = Dataset.from_dict({"data": [recipe_data]})
78
-
79
- # Push the updated dataset to the Hugging Face Hub
80
- dataset.push_to_hub("sharktide/recipes")
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
+