Ryan2219 commited on
Commit
656e46d
·
verified ·
1 Parent(s): 679ac66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -3
app.py CHANGED
@@ -14,10 +14,85 @@ import matplotlib.pyplot as plt
14
  import openai
15
  from datetime import datetime
16
  import threading
 
 
 
 
 
 
17
 
18
  os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
19
  os.environ["GEMINI_API_KEY"] = os.getenv("GEMINI_API_KEY")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # Global state for the interface
22
  class InterfaceState:
23
  def __init__(self):
@@ -1056,7 +1131,20 @@ def agent_worker(user_question):
1056
  state.done = True
1057
 
1058
 
1059
- def run_agentic_workflow(user_question):
 
 
 
 
 
 
 
 
 
 
 
 
 
1060
  state.done = False
1061
  state.final_answer = ""
1062
 
@@ -1101,6 +1189,8 @@ def run_agentic_workflow(user_question):
1101
 
1102
  # Build Gradio Interface
1103
  with gr.Blocks(title="AEC Compliance Agent") as demo:
 
 
1104
  gr.Markdown("# 🏗️ AEC Compliance Analysis Agent")
1105
  gr.Markdown("Ask questions about NYC Building Code compliance for your construction drawings.")
1106
 
@@ -1156,6 +1246,5 @@ with gr.Blocks(title="AEC Compliance Agent") as demo:
1156
 
1157
  if __name__ == "__main__":
1158
  demo.queue().launch(
1159
- inbrowser=True,
1160
- auth=("username", os.getenv("PASSWORD")) # only share the password
1161
  )
 
14
  import openai
15
  from datetime import datetime
16
  import threading
17
+ from huggingface_hub import hf_hub_download, HfApi
18
+ from huggingface_hub.utils import EntryNotFoundError
19
+
20
+ USAGE_DATASET_REPO = os.environ.get("USAGE_DATASET_REPO", "NYSERDA-CRE-Working-Group/nyserda_demo_useage_store")
21
+ USAGE_FILENAME = os.environ.get("USAGE_FILENAME", "usage.csv")
22
+ MAX_RUNS_PER_USER = int(os.environ.get("MAX_RUNS_PER_USER", "10"))
23
 
24
  os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
25
  os.environ["GEMINI_API_KEY"] = os.getenv("GEMINI_API_KEY")
26
+ HF_TOKEN = os.environ.get("HF_TOKEN")
27
+
28
+ client = OpenAI()
29
+ api = HfApi(token=HF_TOKEN)
30
+ def user_id_from_profile(profile: gr.OAuthProfile | None) -> str | None:
31
+ if profile is None:
32
+ return None
33
+ # You said profile.name exists; normalize it.
34
+ # If you later can access preferred_username, use that instead (more unique).
35
+ uid = getattr(profile, "name", None)
36
+ if not uid:
37
+ return None
38
+ return uid.strip().lower()
39
+
40
+ def _load_usage_df() -> pd.DataFrame:
41
+ try:
42
+ local_path = hf_hub_download(
43
+ repo_id=USAGE_DATASET_REPO,
44
+ repo_type="dataset",
45
+ filename=USAGE_FILENAME,
46
+ token=HF_TOKEN,
47
+ )
48
+ return pd.read_csv(local_path)
49
+ except EntryNotFoundError:
50
+ # First run: create empty table
51
+ return pd.DataFrame(columns=["user_id", "runs", "first_seen", "last_seen"])
52
+
53
+ def _save_usage_df(df: pd.DataFrame, commit_message: str) -> None:
54
+ tmp_path = "/tmp/usage.csv"
55
+ df.to_csv(tmp_path, index=False)
56
+
57
+ api.upload_file(
58
+ path_or_fileobj=tmp_path,
59
+ path_in_repo=USAGE_FILENAME,
60
+ repo_id=USAGE_DATASET_REPO,
61
+ repo_type="dataset",
62
+ commit_message=commit_message,
63
+ )
64
+
65
+ def check_and_increment_quota(user_id: str) -> tuple[bool, int]:
66
+ now = int(time.time())
67
+ df = _load_usage_df()
68
+
69
+ if df.empty or (df["user_id"] == user_id).sum() == 0:
70
+ runs = 0
71
+ if runs >= MAX_RUNS_PER_USER:
72
+ return False, 0
73
+ new_row = {
74
+ "user_id": user_id,
75
+ "runs": 1,
76
+ "first_seen": now,
77
+ "last_seen": now,
78
+ }
79
+ df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
80
+ _save_usage_df(df, commit_message=f"usage: increment {user_id} to 1")
81
+ return True, MAX_RUNS_PER_USER - 1
82
 
83
+ idx = df.index[df["user_id"] == user_id][0]
84
+ runs = int(df.loc[idx, "runs"])
85
+
86
+ if runs >= MAX_RUNS_PER_USER:
87
+ return False, 0
88
+
89
+ runs += 1
90
+ df.loc[idx, "runs"] = runs
91
+ df.loc[idx, "last_seen"] = now
92
+
93
+ _save_usage_df(df, commit_message=f"usage: increment {user_id} to {runs}")
94
+ return True, MAX_RUNS_PER_USER - runs
95
+
96
  # Global state for the interface
97
  class InterfaceState:
98
  def __init__(self):
 
1131
  state.done = True
1132
 
1133
 
1134
+ def run_agentic_workflow(user_question, profile: gr.OAuthProfile | None):
1135
+ uid = user_id_from_profile(profile)
1136
+ if uid is None:
1137
+ raise gr.Error("Please sign in with Hugging Face to use this demo.")
1138
+
1139
+ allowed, remaining = check_and_increment_quota(uid)
1140
+ if not allowed:
1141
+ raise gr.Error(f"Usage limit reached: {MAX_RUNS_PER_USER} runs per user.")
1142
+
1143
+ if remaining <= 2:
1144
+ gr.Warning(f"⚠️ Only {remaining} run(s) left!")
1145
+ else:
1146
+ gr.Info(f"✓ Runs remaining: {remaining}")
1147
+
1148
  state.done = False
1149
  state.final_answer = ""
1150
 
 
1189
 
1190
  # Build Gradio Interface
1191
  with gr.Blocks(title="AEC Compliance Agent") as demo:
1192
+ gr.LoginButton()
1193
+
1194
  gr.Markdown("# 🏗️ AEC Compliance Analysis Agent")
1195
  gr.Markdown("Ask questions about NYC Building Code compliance for your construction drawings.")
1196
 
 
1246
 
1247
  if __name__ == "__main__":
1248
  demo.queue().launch(
1249
+ inbrowser=True
 
1250
  )