File size: 3,481 Bytes
9bb0e82
 
b5f31f4
 
 
ca7e5e0
b5f31f4
 
3ebdd53
5d4860e
 
 
5017240
0beeac7
 
2f91ee7
a3ac8df
b5f31f4
a3ac8df
 
3ebdd53
 
ca7e5e0
3ebdd53
ca7e5e0
 
3ebdd53
 
9bb0e82
 
3ebdd53
eb1102e
af16a40
8c7a2d2
 
ecc0b1a
 
9461fe7
eb1102e
 
 
b5f31f4
 
 
 
 
 
 
665a288
 
 
ca7e5e0
665a288
 
 
 
 
 
 
 
 
27aef2e
5410c37
27aef2e
 
 
 
ca7e5e0
27aef2e
 
ca7e5e0
 
27aef2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f30b258
 
 
 
665a288
0beeac7
27aef2e
 
ca7e5e0
 
 
27aef2e
 
 
 
 
 
 
ca7e5e0
1d6829a
ecc0b1a
 
9461fe7
27aef2e
 
 
 
 
 
 
 
665a288
b5f31f4
665a288
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import json
import os
from datasets import Dataset, DatasetDict, DatasetInfo
from huggingface_hub import login, HfApi, CommitScheduler, logging
from typing import List
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime
from pathlib import Path
from uuid import uuid4
import requests

logging.set_verbosity_debug()


# Initialize FastAPI
app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins (temp)
    allow_credentials=True,
    allow_methods=["*"],  
    allow_headers=["*"],  
)

TOKEN = os.getenv("token")


class Recipe(BaseModel):
    name: str
    time: str
    creator: str
    category: str
    diff: str
    description: str
    ingredients: List[str]
    instructions: str

DATASET_PATH = "/app/data"

if not os.path.exists(DATASET_PATH):
    os.makedirs(DATASET_PATH)

login(token=TOKEN)

JSON_DATASET_DIR = Path("json_dataset")
JSON_DATASET_DIR.mkdir(parents=True, exist_ok=True)


JSON_DATASET_PATH = JSON_DATASET_DIR / f"train-{uuid4()}.json"

scheduler = CommitScheduler(
    repo_id="sharktide/recipes",
    repo_type="dataset",
    folder_path=JSON_DATASET_DIR,
    path_in_repo="data",
)

def check_huggingface_recipe_name(name: str) -> bool:
    url = "https://datasets-server.huggingface.co/first-rows?dataset=sharktide%2Frecipes&config=default&split=train"
    response = requests.get(url)
    
    if response.status_code == 200:
        data = response.json()
        
        existing_names = [row['row']['name'] for row in data['rows']]
        return name in existing_names
    if response.status_code == 404:
        return False
    else:
        raise HTTPException(status_code=500, detail="Error accessing store")


def check_local_cache_recipe_name(name: str) -> bool:
    for file in os.listdir(JSON_DATASET_DIR):
        file_path = JSON_DATASET_DIR / file
        if file_path.suffix == ".json":
            with open(file_path, "r") as f:
                for line in f:
                    try:
                        recipe_data = json.loads(line)
                        if recipe_data['name'] == name:
                            return True
                    except json.JSONDecodeError:
                        continue
    return False


@app.get("/status")
def status():
    return {"status": "200"}


@app.put("/add/recipe")
def add_recipe(recipe: Recipe):
    
    if check_huggingface_recipe_name(recipe.name):
        raise HTTPException(status_code=400, detail="Recipe name already exists in the store.")
    
    if check_local_cache_recipe_name(recipe.name):
        raise HTTPException(status_code=400, detail="Recipe name already exists in the local cache.")
    
    try:
        with JSON_DATASET_PATH.open("a") as f:
            json.dump({
                "name": recipe.name,
                "time": recipe.time,
                "creator": recipe.creator,
                "category": recipe.category,
                "diff": recipe.diff,
                "description": recipe.description,
                "ingredients": recipe.ingredients,
                "instructions": recipe.instructions
            }, f)
            f.write("\n")
        return {"Status": "Recipe added successfully."}
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error saving recipe: {str(e)}")