sharktide commited on
Commit
b5f31f4
·
verified ·
1 Parent(s): 45059a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -47
app.py CHANGED
@@ -1,15 +1,14 @@
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
- from pathlib import Path
10
- from uuid import uuid4
11
 
12
- # Initialize FastAPI app
13
  app = FastAPI()
14
 
15
  app.add_middleware(
@@ -20,55 +19,42 @@ app.add_middleware(
20
  allow_headers=["*"], # Allow all headers
21
  )
22
 
23
- # Token for Hugging Face (using the token environment variable as 'token')
24
  TOKEN = os.getenv("token")
25
- if not TOKEN:
26
- raise ValueError("The 'token' environment variable is missing.")
27
-
28
- # Authenticate with Hugging Face Hub
29
- login(token=TOKEN)
30
-
31
- # Hugging Face API for dataset handling
32
- hf_api = HfApi()
33
 
34
- # Define the folder for storing the dataset locally
35
- JSON_DATASET_DIR = "json_dataset"
36
- os.makedirs(JSON_DATASET_DIR, exist_ok=True)
37
 
38
- # Dataset info (to be used when pushing to Hugging Face Hub)
39
- dataset_repo = "sharktide/recipes" # Change to your repo name on Hugging Face Hub
40
- DATASET_PATH = os.path.join(JSON_DATASET_DIR, "data")
41
-
42
- # Define the Recipe model
43
  class Recipe(BaseModel):
44
  ingredients: List[str]
45
  instructions: str
46
 
 
 
 
 
 
 
 
 
 
47
  @app.put("/add/recipe")
48
  async def add_recipe(filename: str, recipe: Recipe):
49
- # Define the file path for saving the recipe in JSON format
50
- file_path = os.path.join(JSON_DATASET_DIR, f"{filename}.json")
51
-
52
- # Prepare the data to be saved
53
- recipe_data = recipe.dict()
54
- recipe_data["datetime"] = datetime.now().isoformat() # Add timestamp to the entry
55
-
56
- # Save the recipe to the JSON file
57
- try:
58
- # Append the recipe data to the JSON file
59
- with open(file_path, "a") as f:
60
- json.dump(recipe_data, f)
61
- f.write("\n") # Add a newline after each entry
62
 
63
- # Now push this dataset file to Hugging Face dataset repo
64
- hf_api.upload_file(
65
- path_or_fileobj=file_path,
66
- path_in_repo=f"data/{filename}.json",
67
- repo_id=dataset_repo,
68
- token=TOKEN
69
- )
70
 
71
- return {"message": f"Recipe '{filename}' added and pushed to Hugging Face dataset."}
72
-
 
 
 
 
 
 
 
 
 
 
73
  except Exception as e:
74
- raise HTTPException(status_code=500, detail=f"Error writing file: {str(e)}")
 
 
 
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(
 
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 = "/app/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)}")