Ruzgar ????? commited on
Commit
8455b5e
·
verified ·
1 Parent(s): caadcc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -147
app.py CHANGED
@@ -1,151 +1,122 @@
1
- from pathlib import Path
2
- from typing import List, Dict, Tuple
3
- import matplotlib.colors as mpl_colors
4
-
5
- import pandas as pd
6
- import seaborn as sns
7
- import shinyswatch
8
-
9
- from shiny import App, Inputs, Outputs, Session, reactive, render, req, ui
10
-
11
- sns.set_theme()
12
-
13
- www_dir = Path(__file__).parent.resolve() / "www"
14
-
15
- df = pd.read_csv(Path(__file__).parent / "penguins.csv", na_values="NA")
16
- numeric_cols: List[str] = df.select_dtypes(include=["float64"]).columns.tolist()
17
- species: List[str] = df["Species"].unique().tolist()
18
- species.sort()
19
-
20
- app_ui = ui.page_fillable(
21
- shinyswatch.theme.minty(),
22
- ui.layout_sidebar(
23
- ui.sidebar(
24
- # Artwork by @allison_horst
25
- ui.input_selectize(
26
- "xvar",
27
- "X variable",
28
- numeric_cols,
29
- selected="Bill Length (mm)",
30
- ),
31
- ui.input_selectize(
32
- "yvar",
33
- "Y variable",
34
- numeric_cols,
35
- selected="Bill Depth (mm)",
36
- ),
37
- ui.input_checkbox_group(
38
- "species", "Filter by species", species, selected=species
39
- ),
40
- ui.hr(),
41
- ui.input_switch("by_species", "Show species", value=True),
42
- ui.input_switch("show_margins", "Show marginal plots", value=True),
43
- ),
44
- ui.output_ui("value_boxes"),
45
- ui.output_plot("scatter", fill=True),
46
- ui.help_text(
47
- "Artwork by ",
48
- ui.a("@allison_horst", href="https://twitter.com/allison_horst"),
49
- class_="text-end",
50
- ),
51
- ),
52
- )
53
-
54
-
55
- def server(input: Inputs, output: Outputs, session: Session):
56
- @reactive.Calc
57
- def filtered_df() -> pd.DataFrame:
58
- """Returns a Pandas data frame that includes only the desired rows"""
59
-
60
- # This calculation "req"uires that at least one species is selected
61
- req(len(input.species()) > 0)
62
-
63
- # Filter the rows so we only include the desired species
64
- return df[df["Species"].isin(input.species())]
65
-
66
- @output
67
- @render.plot
68
- def scatter():
69
- """Generates a plot for Shiny to display to the user"""
70
-
71
- # The plotting function to use depends on whether margins are desired
72
- plotfunc = sns.jointplot if input.show_margins() else sns.scatterplot
73
-
74
- plotfunc(
75
- data=filtered_df(),
76
- x=input.xvar(),
77
- y=input.yvar(),
78
- palette=palette,
79
- hue="Species" if input.by_species() else None,
80
- hue_order=species,
81
- legend=False,
82
- )
83
-
84
- @output
85
- @render.ui
86
- def value_boxes():
87
- df = filtered_df()
88
-
89
- def penguin_value_box(title: str, count: int, bgcol: str, showcase_img: str):
90
- return ui.value_box(
91
- title,
92
- count,
93
- {"class_": "pt-1 pb-0"},
94
- showcase=ui.fill.as_fill_item(
95
- ui.tags.img(
96
- {"style": "object-fit:contain;"},
97
- src=showcase_img,
98
- )
99
- ),
100
- theme_color=None,
101
- style=f"background-color: {bgcol};",
102
- )
103
-
104
- if not input.by_species():
105
- return penguin_value_box(
106
- "Penguins",
107
- len(df.index),
108
- bg_palette["default"],
109
- # Artwork by @allison_horst
110
- showcase_img="penguins.png",
111
- )
112
-
113
- value_boxes = [
114
- penguin_value_box(
115
- name,
116
- len(df[df["Species"] == name]),
117
- bg_palette[name],
118
- # Artwork by @allison_horst
119
- showcase_img=f"{name}.png",
120
- )
121
- for name in species
122
- # Only include boxes for _selected_ species
123
- if name in input.species()
124
- ]
125
-
126
- return ui.layout_column_wrap(*value_boxes, width = 1 / len(value_boxes))
127
-
128
-
129
- # "darkorange", "purple", "cyan4"
130
- colors = [[255, 140, 0], [160, 32, 240], [0, 139, 139]]
131
- colors = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in colors]
132
-
133
- palette: Dict[str, Tuple[float, float, float]] = {
134
- "Adelie": colors[0],
135
- "Chinstrap": colors[1],
136
- "Gentoo": colors[2],
137
- "default": sns.color_palette()[0], # type: ignore
138
  }
139
 
140
- bg_palette = {}
141
- # Use `sns.set_style("whitegrid")` to help find approx alpha value
142
- for name, col in palette.items():
143
- # Adjusted n_colors until `axe` accessibility did not complain about color contrast
144
- bg_palette[name] = mpl_colors.to_hex(sns.light_palette(col, n_colors=7)[1]) # type: ignore
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
- app = App(
148
- app_ui,
149
- server,
150
- static_assets=str(www_dir),
151
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from flask import Flask, request, jsonify
3
+ from dotenv import load_dotenv
4
+ from pymongo import MongoClient
5
+ import openai
6
+ from datetime import datetime
7
+
8
+ load_dotenv()
9
+
10
+ app = Flask(__name__)
11
+
12
+ # MongoDB bağlantısı
13
+ client = MongoClient(os.getenv("MONGODB_URI"))
14
+ db = client[os.getenv("MONGODB_DB_NAME")]
15
+
16
+ # OpenAI API anahtarı
17
+ openai.api_key = os.getenv("OPENAI_API_KEY")
18
+
19
+ # Model grupları ve modeller
20
+ MODEL_GROUPS = {
21
+ "GPT4_GROUP": ["gpt-4", "gpt-4-0125-preview", "gpt-4-0613", "gpt-4-1106-preview"],
22
+ "GPT4_TURBO_GROUP": ["gpt-4-turbo", "gpt-4-turbo-preview"],
23
+ "GPT35_GROUP": ["gpt-3.5-turbo", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-1106"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
+ MODELS = {
27
+ "GPT4": MODEL_GROUPS["GPT4_GROUP"] + MODEL_GROUPS["GPT4_TURBO_GROUP"],
28
+ "GPT35": MODEL_GROUPS["GPT35_GROUP"],
29
+ "IMAGE": ["dall-e-2", "dall-e-3"],
30
+ }
31
 
32
+ # Kullanıcı seviyeleri
33
+ TIERS = {
34
+ 1: {
35
+ "models": MODELS["GPT35"],
36
+ "limits": {"daily": 100, "GPT35_GROUP": 100}
37
+ },
38
+ 2: {
39
+ "models": MODELS["GPT35"] + MODELS["GPT4"],
40
+ "limits": {"daily": 500, "GPT35_GROUP": 300, "GPT4_GROUP": 150, "GPT4_TURBO_GROUP": 50}
41
+ },
42
+ 3: {
43
+ "models": MODELS["GPT35"] + MODELS["GPT4"] + MODELS["IMAGE"],
44
+ "limits": {"daily": 1000, "GPT35_GROUP": 500, "GPT4_GROUP": 300, "GPT4_TURBO_GROUP": 100, "dall-e-2": 50, "dall-e-3": 25}
45
+ }
46
+ }
47
 
48
+ def get_user_tier(api_key):
49
+ user = db.users.find_one({"api_key": api_key})
50
+ if user:
51
+ return user["tier"]
52
+ for i in range(1, 4):
53
+ if os.getenv(f"USER_{i}_API_KEY") == api_key:
54
+ return int(os.getenv(f"USER_{i}_TIER"))
55
+ return None
56
+
57
+ def get_model_group(model):
58
+ for group, models in MODEL_GROUPS.items():
59
+ if model in models:
60
+ return group
61
+ return model
62
+
63
+ def check_rate_limit(api_key, tier, model):
64
+ now = datetime.now()
65
+ today = now.date().isoformat()
66
+ model_group = get_model_group(model)
67
+
68
+ usage = db.usage.find_one_and_update(
69
+ {"api_key": api_key, "date": today},
70
+ {"$inc": {"daily": 1, model_group: 1}},
71
+ upsert=True,
72
+ return_document=True
73
+ )
74
+
75
+ tier_limits = TIERS[tier]["limits"]
76
+ if usage["daily"] > tier_limits["daily"]:
77
+ raise Exception("Daily rate limit exceeded")
78
+ if usage.get(model_group, 0) > tier_limits.get(model_group, float("inf")):
79
+ raise Exception(f"Rate limit for {model_group} exceeded")
80
+
81
+ @app.route('/v1/chat/completions', methods=['POST'])
82
+ def chat_completions():
83
+ data = request.json
84
+ api_key = request.headers.get('Authorization', '').replace('Bearer ', '')
85
+
86
+ user_tier = get_user_tier(api_key)
87
+ if not user_tier:
88
+ return jsonify({"error": "Invalid API key"}), 401
89
+
90
+ model = data.get('model')
91
+ if model not in TIERS[user_tier]["models"]:
92
+ return jsonify({"error": "Model not available for your tier"}), 403
93
+
94
+ try:
95
+ check_rate_limit(api_key, user_tier, model)
96
+ response = openai.ChatCompletion.create(**data)
97
+ return jsonify(response)
98
+ except Exception as e:
99
+ return jsonify({"error": str(e)}), 429
100
+
101
+ @app.route('/v1/images/generations', methods=['POST'])
102
+ def image_generations():
103
+ data = request.json
104
+ api_key = request.headers.get('Authorization', '').replace('Bearer ', '')
105
+
106
+ user_tier = get_user_tier(api_key)
107
+ if not user_tier:
108
+ return jsonify({"error": "Invalid API key"}), 401
109
+
110
+ model = data.get('model', 'dall-e-2')
111
+ if model not in TIERS[user_tier]["models"]:
112
+ return jsonify({"error": "Model not available for your tier"}), 403
113
+
114
+ try:
115
+ check_rate_limit(api_key, user_tier, model)
116
+ response = openai.Image.create(**data)
117
+ return jsonify(response)
118
+ except Exception as e:
119
+ return jsonify({"error": str(e)}), 429
120
+
121
+ if __name__ == '__main__':
122
+ app.run(host='0.0.0.0', port=7860)