Spaces:
Sleeping
Sleeping
upload dataset
Browse filesFiles changed (13)
- Dockerfile+16-2
- app.py+116-34
- backup/2025-10-23/new_user.jsonAdded+1
- backup/2025-10-23/test_user_1.jsonAdded+1
- backup/2025-10-23/test_user_2.jsonAdded+1
- crontabAdded+4
- last_push_date.txtAdded+1
- requirements.txt+3
- start.py+47
- start_server.shAdded+60
- start_with_cron.shAdded+26
- test_api.sh+17-26
- upload_hf_dataset.pyAdded+108
5 unmodified lines67891011123 unmodified lines1617181920212223242526272829303121223233343536375 unmodified lines# μμ€ν
ν¨ν€μ§ μ
λ°μ΄νΈ λ° νμν ν¨ν€μ§ μ€μΉRUN apt-get update && apt-get install -y \ build-essential \ cron \ && rm -rf /var/lib/apt/lists/*
# requirements λ³΅μ¬ λ° μ€μΉ3 unmodified lines# μ ν리μΌμ΄μ
μ½λ 볡μ¬COPY . .
# cron μ€μ νμΌ λ³΅μ¬COPY crontab /etc/cron.d/batch-push-cron
# cron κΆν μ€μ RUN chmod 0644 /etc/cron.d/batch-push-cronRUN crontab /etc/cron.d/batch-push-cron
# λ‘κ·Έ λλ ν 리 μμ±RUN mkdir -p /var/log
# Hugging Face Spaceλ ν¬νΈ 7860μ μ¬μ©ν©λλ€EXPOSE 7860
# start.pyλ‘ μλ² μ€ν (Wallet μλ λμ½λ©)CMD ["python", "start.py"]# μμ μ€ν¬λ¦½νΈ λ³΅μ¬ λ° μ€νCOPY start_with_cron.sh /start_with_cron.shRUN chmod +x /start_with_cron.sh
CMD ["/start_with_cron.sh"]
123445678910111213141516177 unmodified lines2526272829303132333421 unmodified lines5657584950515253545556575859605960618 unmodified lines7071727573747576787778798081828384858687888990919293949596979899100101102891031049110510610710837 unmodified lines146147148135136149150151152153138139140141154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196143144145146147148149150151152197154198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236import osimport jsonfrom typing import List, Optionalfrom fastapi import FastAPI, HTTPExceptionfrom fastapi import FastAPI, HTTPException, Requestfrom pydantic import BaseModel, Field, ConfigDictfrom typing import Listimport oracledbfrom dotenv import load_dotenvimport jsonimport osimport requestsimport pandas as pdfrom datetime import datetimefrom datasets import Dataset, DatasetDict, load_dataset
# λ‘컬 κ°λ°: .env νμΌ λ‘λ (μμΌλ©΄)load_dotenv()7 unmodified lines# tnsnames.ora μμ alias νμΈ (λ³΄ν΅ *_high)TNS_ALIAS = os.environ.get("DB_TNS_ALIAS", "musclecare_high")
# Hugging Face μ€μ HF_DATA_REPO_ID = os.getenv("HF_DATA_REPO_ID")HF_DATA_TOKEN = os.getenv("HF_DATA_TOKEN")
# ----- μ°κ²° ν: Thin + mTLS (μ§κ°) -----# μ λ νΈμΆνμ§ λ§μΈμ: oracledb.init_oracle_client() # (Thickλ‘ λΉ μ Έμ μ€ν¨ κ°λ₯)pool: oracledb.ConnectionPool = oracledb.create_pool(21 unmodified lines user_emb: Optional[List[float]] = Field(default=None, description="length=12") model_version: Optional[str] = None
class LogItem(BaseModel): user_id: str session_id: Optional[str] = None measure_date: str # 'YYYY-MM-DD' rms: Optional[float] = None freq: Optional[float] = None fatigue: Optional[float] = None mode: Optional[str] = Field(default="EMA", description="EMA/Hybrid/E2E") window_count: Optional[int] = None
class LogsPayload(BaseModel): items: List[LogItem] = Field(..., min_length=1)
# ----- μ νΈ -----def clob_json(obj) -> str:8 unmodified lines "message": "MuscleCare API Server", "version": "1.0.0", "endpoints": { "health": "/health", "health": "/health (λΉ λ₯Έ 체ν¬)", "health_db": "/health/db (DB μ°κ²° 체ν¬)", "docs": "/docs", "upload_state": "/upload_state", "upload_logs": "/upload_logs" "upload_dataset": "/upload_dataset", "user_dataset": "/user_dataset/{user_id}" } }
@app.get("/health")def health(): try: # κ°λ¨ν health μ²΄ν¬ - DB μ°κ²° μμ΄ μλ² μνλ§ νμΈ return { "ok": True, "server": "running", "timestamp": datetime.now().isoformat(), "status": "healthy" } except Exception as e: return {"ok": False, "error": str(e)}
@app.get("/health/db")def health_db(): """DB μ°κ²°μ ν¬ν¨ν μμΈ health 체ν¬""" try: with pool.acquire() as conn: with conn.cursor() as cur: cur.execute("SELECT 1 FROM DUAL") v = cur.fetchone()[0] return {"ok": True, "db": v} return {"ok": True, "db": v, "server": "running"} except Exception as e: raise HTTPException(500, f"DB health check failed: {e}") return {"ok": False, "db": "error", "error": str(e)}
@app.post("/upload_state")def upload_state(p: StatePayload):37 unmodified lines except Exception as e: raise HTTPException(500, f"upload_state failed: {e}")
@app.post("/upload_logs")def upload_logs(body: LogsPayload):
@app.post("/upload_dataset")async def upload_to_dataset(request: Request): """λ‘컬 νμΌμ μ¬μ©μλ³ λ°μ΄ν° μ μ₯""" try: rows = [( it.user_id, it.session_id, it.measure_date, it.rms, it.freq, it.fatigue, it.mode, it.window_count ) for it in body.items] data = await request.json() user_id = data.get("user_id")
if not user_id: raise HTTPException(status_code=400, detail="user_idκ° νμν©λλ€")
# λ°μ΄ν°μ νμμ€ν¬ν μΆκ° data["timestamp"] = datetime.now().isoformat() # λ‘컬 λ°μ΄ν° λλ ν 리 μμ± data_dir = "user_data" os.makedirs(data_dir, exist_ok=True) # μ¬μ©μλ³ JSON νμΌ κ²½λ‘ user_file = os.path.join(data_dir, f"{user_id}.json") # κΈ°μ‘΄ λ°μ΄ν° λ‘λ existing_data = [] if os.path.exists(user_file): try: with open(user_file, 'r', encoding='utf-8') as f: existing_data = json.load(f) print(f"π κΈ°μ‘΄ λ°μ΄ν° λ‘λ: {user_id} ({len(existing_data)}κ° λ μ½λ)") except: existing_data = [] # μ λ°μ΄ν° μΆκ° existing_data.append(data) # νμΌ μ μ₯ with open(user_file, 'w', encoding='utf-8') as f: json.dump(existing_data, f, ensure_ascii=False, indent=2) print(f"β
λ‘컬 νμΌ μ μ₯ μλ£: {user_id} ({len(existing_data)}κ° λ μ½λ)") return { "user_id": user_id, "rows": len(existing_data), "status": "success", "filename": f"{user_id}.json", "file_path": user_file, "message": f"Data saved to local file: {user_file}" }
with pool.acquire() as conn: with conn.cursor() as cur: cur.executemany(""" INSERT INTO MuscleCare.fatigue_logs (user_id, session_id, measure_date, rms, freq, fatigue, mode, window_count, created_at) VALUES (:1, :2, TO_DATE(:3,'YYYY-MM-DD'), :4, :5, :6, :7, :8, CURRENT_TIMESTAMP) """, rows) conn.commit() return {"ok": True, "inserted": len(rows)} except Exception as e: raise HTTPException(500, f"upload_logs failed: {e}") print(f"β λ‘컬 μ μ₯ μ€ν¨: {e}") raise HTTPException(status_code=500, detail=f"λ‘컬 μ μ₯ μ€ν¨: {str(e)}")
@app.get("/user_dataset/{user_id}")async def read_user_dataset(user_id: str): """λ‘컬 νμΌμμ μ¬μ©μ λ°μ΄ν° μ‘°ν""" try: # μ¬μ©μλ³ JSON νμΌ κ²½λ‘ data_dir = "user_data" user_file = os.path.join(data_dir, f"{user_id}.json") if not os.path.exists(user_file): return { "user_id": user_id, "count": 0, "recent_data": [], "source": "local_file", "message": "No data found" } # λ°μ΄ν° λ‘λ with open(user_file, 'r', encoding='utf-8') as f: data = json.load(f) # μ΅κ·Ό 5κ° λ μ½λ λ°ν recent_data = data[-5:] if len(data) > 5 else data return { "user_id": user_id, "count": len(data), "recent_data": recent_data, "filename": f"{user_id}.json", "source": "local_file" } except Exception as e: print(f"β λ‘컬 μ‘°ν μ€ν¨: {e}") raise HTTPException(status_code=500, detail=f"λ‘컬 μ‘°ν μ€ν¨: {str(e)}")
1[{"user_id": "new_user", "rms": 0.95, "freq": 60.1, "fatigue": 0.88, "timestamp": "2025-10-23T15:02:00.000000"}]1[{"user_id": "test_user_1", "rms": 0.85, "freq": 52.3, "fatigue": 0.72, "timestamp": "2025-10-23T14:55:00.000000"}]1[{"user_id": "test_user_2", "rms": 0.91, "freq": 58.7, "fatigue": 0.81, "timestamp": "2025-10-23T14:55:30.000000"}]1234# λ§€μΌ μμ μ λ°°μΉ νΈμ μ€ν0 0 * * * cd /app && python upload_hF_dataset.py >> /var/log/batch_push.log 2>&1
# λΉ μ€ νμ (cron μꡬμ¬ν)12025-10-233 unmodified lines4567893 unmodified linesoracledb>=2.3pydanticpython-dotenvdatasetspandasrequests4 unmodified lines5678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535445 unmodified lines1001011021031041051061071084 unmodified lines# .env νμΌ λ‘λ (λ‘컬 κ°λ°μ©)load_dotenv()
def setup_environment(): """ νκ²½λ³μ μλ μ€μ : - λ‘컬: .env νμΌμμ λ‘λ - Hugging Face Space: νκ²½λ³μμμ μλ μ€μ """ print("π§ νκ²½λ³μ μ€μ μ€...") # Hugging Face Dataset μ€μ (κΈ°λ³Έκ° μ€μ ) if not os.getenv("HF_DATA_REPO_ID"): os.environ["HF_DATA_REPO_ID"] = "Merry99/musclecare-data" print("π HF_DATA_REPO_ID κΈ°λ³Έκ° μ€μ : Merry99/musclecare-data") if not os.getenv("HF_DATA_TOKEN"): os.environ["HF_DATA_TOKEN"] = "hf_dummy_token_for_testing" print("π HF_DATA_TOKEN κΈ°λ³Έκ° μ€μ : hf_dummy_token_for_testing") # Oracle DB μ€μ νμΈ required_vars = ["DB_USER", "DB_PASSWORD", "WALLET_DIR", "WALLET_PASSWORD"] missing_vars = [] for var in required_vars: if not os.getenv(var): missing_vars.append(var) if missing_vars: print(f"β οΈ λλ½λ νκ²½λ³μ: {', '.join(missing_vars)}") print("π‘ .env νμΌμ νμΈνκ±°λ νκ²½λ³μλ₯Ό μ€μ ν΄μ£ΌμΈμ.") # λ‘컬 κ°λ°μ μν κΈ°λ³Έκ° μ€μ (κ²½κ³ μ ν¨κ») if not os.getenv("DB_USER"): os.environ["DB_USER"] = "ADMIN" print("π DB_USER κΈ°λ³Έκ° μ€μ : ADMIN") if not os.getenv("DB_PASSWORD"): os.environ["DB_PASSWORD"] = "YourDBPassword123!" print("π DB_PASSWORD κΈ°λ³Έκ° μ€μ : YourDBPassword123!") if not os.getenv("WALLET_PASSWORD"): os.environ["WALLET_PASSWORD"] = "YourWalletPassword123!" print("π WALLET_PASSWORD κΈ°λ³Έκ° μ€μ : YourWalletPassword123!") else: print("β
λͺ¨λ νμ νκ²½λ³μκ° μ€μ λμμ΅λλ€") print("π§ νκ²½λ³μ μ€μ μλ£")
def prepare_wallet_dir(): """ Wallet μ€λΉ:45 unmodified lines print("π MuscleCare FastAPI μλ² μμ") print("=" * 60) # νκ²½λ³μ μλ μ€μ setup_environment() # Wallet μ€λΉ try: prepare_wallet_dir()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960#!/bin/bash
# MuscleCare FastAPI μλ² μμ μ€ν¬λ¦½νΈ
echo "======================================"echo "π MuscleCare FastAPI μλ² μμ"echo "======================================"
# .env νμΌ λ‘λ (μ νμ¬ν)if [ -f .env ]; then echo "π .env νμΌ λ‘λ μ€..." export $(cat .env | grep -v '^#' | xargs) echo "β
.env νμΌ λ‘λ μλ£"else echo "π .env νμΌμ΄ μμ΅λλ€. start.pyμμ μλμΌλ‘ νκ²½λ³μλ₯Ό μ€μ ν©λλ€."fi
echo "π§ νκ²½λ³μλ start.pyμμ μλμΌλ‘ μ€μ λ©λλ€."
# Python μμ‘΄μ± νμΈ λ° μ€μΉecho "π¦ Python μμ‘΄μ± νμΈ μ€..."if ! python3 -c "import fastapi, uvicorn, oracledb" 2>/dev/null; then echo "β νμ Python ν¨ν€μ§κ° μ€μΉλμ§ μμμ΅λλ€." echo "π§ μλ μ€μΉλ₯Ό μμν©λλ€..." # pip3 μ¬μ© μλ if command -v pip3 &> /dev/null; then echo "π₯ pip3λ‘ ν¨ν€μ§ μ€μΉ μ€..." pip3 install -r requirements.txt # pip μ¬μ© μλ elif command -v pip &> /dev/null; then echo "π₯ pipμΌλ‘ ν¨ν€μ§ μ€μΉ μ€..." pip install -r requirements.txt # python -m pip μ¬μ© μλ else echo "π₯ python -m pipμΌλ‘ ν¨ν€μ§ μ€μΉ μ€..." python3 -m pip install -r requirements.txt fi # μ€μΉ ν λ€μ νμΈ if ! python3 -c "import fastapi, uvicorn, oracledb" 2>/dev/null; then echo "β ν¨ν€μ§ μ€μΉμ μ€ν¨νμ΅λλ€." echo "π‘ μλμΌλ‘ μ€μΉν΄μ£ΌμΈμ:" echo " pip3 install -r requirements.txt" exit 1 fifi
echo "β
Python μμ‘΄μ± νμΈ μλ£"
# μλ² μμecho ""echo "π FastAPI μλ² μμ μ€..."echo "π μλ² μ£Όμ: http://localhost:7860"echo "π API λ¬Έμ: http://localhost:7860/docs"echo "π μ’
λ£νλ €λ©΄ Ctrl+Cλ₯Ό λλ₯΄μΈμ"echo ""
# μλ² μ€νpython3 start.py1234567891011121314151617181920212223242526#!/bin/bash
# λ‘κ·Έ λλ ν 리 μμ±mkdir -p /var/log
# cron μλΉμ€ μμservice cron start
# cron μν νμΈecho "π
Cron μλΉμ€ μμλ¨"crontab -l
# FastAPI μλ² μμ (λ°±κ·ΈλΌμ΄λ)echo "π FastAPI μλ² μμ..."python start.py &
# μλ²κ° μμλ λκΉμ§ λκΈ°sleep 5
# μλ² μν νμΈecho "π μλ² μν νμΈ..."curl -s http://localhost:7860/health || echo "β οΈ μλ² μμ μ€..."
# λ‘κ·Έ λͺ¨λν°λ§ (μ νμ¬ν)echo "π λ°°μΉ νΈμ λ‘κ·Έ λͺ¨λν°λ§ μμ..."tail -f /var/log/batch_push.log &1123432 unmodified lines37383940414041424343444546474849505152535455565758596061626364656667684748495051525354555657585960616263646566#!/bin/bashγ
γ
#!/bin/bash
# MuscleCare API ν
μ€νΈ μ€ν¬λ¦½νΈ
32 unmodified linesecho ""echo ""
# 3. νΌλ‘λ λ‘κ·Έ μ
λ‘λecho "3οΈβ£ νΌλ‘λ λ‘κ·Έ μ
λ‘λ"# 3. Dataset μ
λ‘λecho "3οΈβ£ Dataset μ
λ‘λ"echo "--------------------------------------"curl -X POST "$BASE_URL/upload_logs" \curl -X POST "$BASE_URL/upload_dataset" \ -H "Content-Type: application/json" \ -H "accept: application/json" \ -d '{ "items": [ { "user_id": "test_user_001", "session_id": "session_001", "measure_date": "2025-10-22", "rms": 0.12, "freq": 49.8, "fatigue": 0.83, "mode": "Hybrid", "window_count": 100 }, { "user_id": "test_user_001", "session_id": "session_002", "measure_date": "2025-10-22", "rms": 0.15, "freq": 48.5, "fatigue": 0.91, "mode": "E2E", "window_count": 120 } ] "user_id": "test_user_001", "rms": 0.42, "freq": 45.3, "fatigue": 0.25, "timestamp": "2024-01-15T10:30:00Z" }' | jq .echo ""echo ""
# 4. μ¬μ©μ Dataset μ‘°νecho "4οΈβ£ μ¬μ©μ Dataset μ‘°ν"echo "--------------------------------------"curl -X GET "$BASE_URL/user_dataset/test_user_001" \ -H "accept: application/json" | jq .echo ""echo ""
echo "======================================"echo "β
ν
μ€νΈ μλ£"echo "======================================"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108from datasets import Dataset, DatasetDictfrom datetime import datetime, dateimport pandas as pd, glob, json, os, shutilfrom dotenv import load_dotenv
load_dotenv()
HF_DATA_REPO_ID = os.getenv("HF_DATA_REPO_ID")HF_DATA_TOKEN = os.getenv("HF_DATA_TOKEN")CACHE_DIR = "./user_data"BACKUP_DIR = "./backup"LAST_PUSH_FILE = "./last_push_date.txt"
def now_str(): return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_last_push_date(): """λ§μ§λ§ νΈμ λ μ§ λ°ν""" if os.path.exists(LAST_PUSH_FILE): with open(LAST_PUSH_FILE, "r") as f: return f.read().strip() return None
def update_last_push_date(): """λ§μ§λ§ νΈμ λ μ§ κΈ°λ‘""" with open(LAST_PUSH_FILE, "w") as f: f.write(str(date.today()))
def should_push_today(): """μ€λ νΈμ μ¬λΆ νμΈ""" last_push = get_last_push_date() today = str(date.today()) return last_push != today
def batch_push_to_huggingface(): """ν루 1ν Hugging Face Dataset μ
λ‘λ""" # νμ νκ²½λ³μ νμΈ if not HF_DATA_REPO_ID or not HF_DATA_TOKEN: print(f"β {now_str()} - νκ²½λ³μ HF_DATA_REPO_ID λλ HF_DATA_TOKENμ΄ μ€μ λμ§ μμμ΅λλ€.") return
# νΈμ μ¬λΆ μ²΄ν¬ if not should_push_today(): print(f"π
{now_str()} - μ΄λ―Έ μ€λ νΈμ μλ£λ¨. μ’
λ£.") return
files = glob.glob(os.path.join(CACHE_DIR, "*.json")) if not files: print(f"π {now_str()} - μΊμλ νμΌμ΄ μμ΅λλ€. μ’
λ£.") return
print(f"π {now_str()} - λ°°μΉ νΈμ μμ ({len(files)}κ° νμΌ)")
user_splits = {} for path in files: user_id = os.path.basename(path).split(".")[0] try: with open(path, "r", encoding="utf-8") as f: records = json.load(f) if not records: print(f"β οΈ {user_id}: λΉμ΄μλ νμΌ, 건λλ") continue
df = pd.DataFrame(records) user_splits[user_id] = Dataset.from_pandas(df) print(f"π {user_id}: {len(records)}κ° λ μ½λ λ³ν μλ£")
except Exception as e: print(f"β {user_id}: νμΌ λ‘λ μ€ν¨ β {e}") continue
if not user_splits: print(f"β {now_str()} - μ²λ¦¬ν λ°μ΄ν°κ° μμ΅λλ€. μ’
λ£.") return
# λ°±μ
λλ ν 리 μμ± os.makedirs(BACKUP_DIR, exist_ok=True) backup_path = os.path.join(BACKUP_DIR, date.today().isoformat()) shutil.copytree(CACHE_DIR, backup_path, dirs_exist_ok=True) print(f"ποΈ {now_str()} - λ°μ΄ν° λ°±μ
μλ£ β {backup_path}")
try: dataset_dict = DatasetDict(user_splits) dataset_dict.push_to_hub(HF_DATA_REPO_ID, token=HF_DATA_TOKEN, private=True) print(f"β
{now_str()} - Hugging Face Hub νΈμ μ±κ³΅ ({len(user_splits)}λͺ
) β {HF_DATA_REPO_ID}")
# νΈμ μ±κ³΅ μ μΊμ μ 리 shutil.rmtree(CACHE_DIR, ignore_errors=True) print(f"ποΈ {now_str()} - user_data λλ ν 리 μμ μλ£")
update_last_push_date() print(f"π
{now_str()} - λ§μ§λ§ νΈμ λ μ§ μ
λ°μ΄νΈ μλ£")
except Exception as e: print(f"β {now_str()} - νΈμ μ€ν¨: {e}") print(f"β οΈ {now_str()} - μΊμ μ μ§ (λ°μ΄ν° μ μ€ λ°©μ§)") # μ€ν¨ μ μΊμ μ μ§ return
def main(): """CLI/cron μ§μ
μ """ try: batch_push_to_huggingface() except Exception as e: print(f"π₯ {now_str()} - μκΈ°μΉ λͺ»ν μ€λ₯ λ°μ: {e}")
if __name__ == "__main__": main()Dockerfile+16-2
app.py+116-34
backup/2025-10-23/new_user.jsonAdded+1
backup/2025-10-23/test_user_1.jsonAdded+1
backup/2025-10-23/test_user_2.jsonAdded+1
crontabAdded+4
last_push_date.txtAdded+1
requirements.txt+3
start.py+47
start_server.shAdded+60
start_with_cron.shAdded+26
test_api.sh+17-26
upload_hf_dataset.pyAdded+108