Hector Salvador [Fisharp] commited on
Commit
32f7b3e
1 Parent(s): ab218e2

Relocation of static contents to their own files

Browse files
README.md CHANGED
@@ -1,13 +1,30 @@
1
  ---
2
- title: BigCode - Playground
3
- emoji: 🪐
4
- colorFrom: grey
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 3.28.3
8
  app_file: app.py
9
- pinned: false
10
  duplicated_from: bigcode/bigcode-playground
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: StarCoder Completion
3
+ emoji: 💫
4
+ colorFrom: gray
5
+ colorTo: blue
6
  sdk: gradio
7
  sdk_version: 3.28.3
8
  app_file: app.py
9
+ pinned: true
10
  duplicated_from: bigcode/bigcode-playground
11
  ---
12
 
13
+
14
+ # StarCoder Demo
15
+
16
+ ## Star💫Coder Code Completion Playground 💻
17
+
18
+ This is a demo playground to generate code with the power of [StarCoder](https://huggingface.co/bigcode/starcoder)💫 a **15B** parameter model for code generation in **80+** programming languages.
19
+
20
+ This is not an instruction model but just a code completion tool.
21
+
22
+ For instruction and chatting you can chat with a prompted version of the model directly at the [HuggingFace Chat 🤗 (hf.co/chat)](https://huggingface.co/chat/?model=starcoder)
23
+
24
+ ---
25
+
26
+ **Intended Use**: this app and its [supporting model](https://huggingface.co/bigcode/starcoder) are provided for demonstration purposes only; not to serve as a replacement for human expertise. For more details on the model's limitations in terms of factuality and biases, please refer to the source [model card](hf.co/bigcode)
27
+
28
+ ⚠️ Any use or sharing of this demo constitutes your acceptance of the BigCode [OpenRAIL-M](https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement) License Agreement and the use restrictions included within.
29
+
30
+ ---
app.py CHANGED
@@ -1,173 +1,150 @@
1
- import json
2
  import os
3
- import shutil
4
- import requests
5
 
6
  import gradio as gr
7
- from huggingface_hub import Repository
8
  from text_generation import Client
9
 
10
- from share_btn import community_icon_html, loading_icon_html, share_js, share_btn_css
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
13
- API_URL = "https://api-inference.huggingface.co/models/bigcode/starcoder/"
14
- API_URL_BASE ="https://api-inference.huggingface.co/models/bigcode/starcoderbase/"
15
-
16
- FIM_PREFIX = "<fim_prefix>"
17
- FIM_MIDDLE = "<fim_middle>"
18
- FIM_SUFFIX = "<fim_suffix>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  FIM_INDICATOR = "<FILL_HERE>"
21
 
22
- FORMATS = """## Model Formats
23
-
24
- The model is pretrained on code and is formatted with special tokens in addition to the pure code data,\
25
- such as prefixes specifying the source of the file or tokens separating code from a commit message.\
26
- Use these templates to explore the model's capacities:
27
-
28
- ### 1. Prefixes 🏷️
29
- For pure code files, use any combination of the following prefixes:
30
-
31
- ```
32
- <reponame>REPONAME<filename>FILENAME<gh_stars>STARS\ncode<|endoftext|>
33
- ```
34
- STARS can be one of: 0, 1-10, 10-100, 100-1000, 1000+
35
-
36
- ### 2. Commits 💾
37
- The commits data is formatted as follows:
38
 
39
- ```
40
- <commit_before>code<commit_msg>text<commit_after>code<|endoftext|>
41
- ```
42
 
43
- ### 3. Jupyter Notebooks 📓
44
- The model is trained on Jupyter notebooks as Python scripts and structured formats like:
45
 
46
- ```
47
- <start_jupyter><jupyter_text>text<jupyter_code>code<jupyter_output>output<jupyter_text>
48
- ```
49
-
50
- ### 4. Issues 🐛
51
- We also trained on GitHub issues using the following formatting:
52
- ```
53
- <issue_start><issue_comment>text<issue_comment>...<issue_closed>
54
- ```
55
-
56
- ### 5. Fill-in-the-middle 🧩
57
- Fill in the middle requires rearranging the model inputs. The playground handles this for you - all you need is to specify where to fill:
58
- ```
59
- code before<FILL_HERE>code after
60
- ```
61
- """
62
 
63
  theme = gr.themes.Monochrome(
64
  primary_hue="indigo",
65
  secondary_hue="blue",
66
  neutral_hue="slate",
67
- radius_size=gr.themes.sizes.radius_sm,
68
  font=[
69
- gr.themes.GoogleFont("Open Sans"),
70
  "ui-sans-serif",
71
  "system-ui",
72
  "sans-serif",
73
  ],
 
74
  )
75
 
76
- client = Client(
77
- API_URL,
78
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
79
- )
80
- client_base = Client(
81
- API_URL_BASE, headers={"Authorization": f"Bearer {HF_TOKEN}"},
82
- )
83
-
84
- def generate(
85
- prompt, temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0, version="StarCoder",
86
- ):
87
-
88
- temperature = float(temperature)
89
- if temperature < 1e-2:
90
- temperature = 1e-2
91
  top_p = float(top_p)
92
- fim_mode = False
93
 
94
  generate_kwargs = dict(
95
- temperature=temperature,
96
- max_new_tokens=max_new_tokens,
97
- top_p=top_p,
98
- repetition_penalty=repetition_penalty,
99
- do_sample=True,
100
- seed=42,
101
  )
102
 
103
- if FIM_INDICATOR in prompt:
104
- fim_mode = True
105
  try:
106
  prefix, suffix = prompt.split(FIM_INDICATOR)
107
- except:
108
- raise ValueError(f"Only one {FIM_INDICATOR} allowed in prompt!")
 
109
  prompt = f"{FIM_PREFIX}{prefix}{FIM_SUFFIX}{suffix}{FIM_MIDDLE}"
110
 
111
- if version == "StarCoder":
112
- stream = client.generate_stream(prompt, **generate_kwargs)
113
- else:
114
- stream = client_base.generate_stream(prompt, **generate_kwargs)
115
 
116
- if fim_mode:
117
- output = prefix
118
- else:
119
- output = prompt
120
 
121
- previous_token = ""
122
  for response in stream:
123
- if response.token.text == "<|endoftext|>":
124
  if fim_mode:
125
  output += suffix
126
  else:
127
  return output
128
  else:
129
  output += response.token.text
130
- previous_token = response.token.text
 
131
  yield output
132
  return output
133
 
134
-
135
  examples = [
136
  "X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.1)\n\n# Train a logistic regression model, predict the labels on the test set and compute the accuracy score",
137
  "// Returns every other value in the array as a new array.\nfunction everyOther(arr) {",
138
  "def alternating(list1, list2):\n results = []\n for i in range(min(len(list1), len(list2))):\n results.append(list1[i])\n results.append(list2[i])\n if len(list1) > len(list2):\n <FILL_HERE>\n else:\n results.extend(list2[i+1:])\n return results",
139
  ]
140
 
141
-
142
  def process_example(args):
143
  for x in generate(args):
144
  pass
145
  return x
146
 
147
 
148
- css = ".generating {visibility: hidden}"
149
-
150
- monospace_css = """
151
- #q-input textarea {
152
- font-family: monospace, 'Consolas', Courier, monospace;
153
- }
154
- """
155
-
156
-
157
- css += share_btn_css + monospace_css + ".gradio-container {color: black}"
158
-
159
-
160
- description = """
161
- <div style="text-align: center;">
162
- <h1> 💫 StarCoder<span style='color: #e6b800;'> - </span>Code Completion Playground 🪐</h1>
163
- <p>This is a demo to generate code with <a href="https://huggingface.co/bigcode/starcoder" style='color: #e6b800;'>StarCoder</a>, a 15B parameter model for code generation in 86 programming languages.
164
- <b>This is not an instruction model</b>. For instruction and chatting you can chat with a prompted version of the model at <a href="https://huggingface.co/chat/?model=bigcode/starcoder">hf.co/chat</a></p>
165
- </div>
166
- """
167
- disclaimer = """⚠️<b>Any use or sharing of this demo constitues your acceptance of the BigCode [OpenRAIL-M](https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement) License Agreement and the use restrictions included within.</b>\
168
- <br>**Intended Use**: this app and its [supporting model](https://huggingface.co/bigcode) are provided for demonstration purposes; not to serve as replacement for human expertise. For more details on the model's limitations in terms of factuality and biases, see the [model card.](hf.co/bigcode)"""
169
-
170
- with gr.Blocks(theme=theme, analytics_enabled=False, css=css) as demo:
171
  with gr.Column():
172
  gr.Markdown(description)
173
  with gr.Row():
@@ -231,8 +208,8 @@ with gr.Blocks(theme=theme, analytics_enabled=False, css=css) as demo:
231
  )
232
  gr.Markdown(disclaimer)
233
  with gr.Group(elem_id="share-btn-container"):
234
- community_icon = gr.HTML(community_icon_html, visible=True)
235
- loading_icon = gr.HTML(loading_icon_html, visible=True)
236
  share_button = gr.Button(
237
  "Share to community", elem_id="share-btn", visible=True
238
  )
@@ -251,4 +228,5 @@ with gr.Blocks(theme=theme, analytics_enabled=False, css=css) as demo:
251
  outputs=[output],
252
  )
253
  share_button.click(None, [], [], _js=share_js)
254
- demo.queue(concurrency_count=16).launch(debug=True)
 
 
1
+ import sys
2
  import os
 
 
3
 
4
  import gradio as gr
5
+ from gradio.themes.utils import sizes
6
  from text_generation import Client
7
 
8
+ # todo: remove and replace by the actual js file instead
9
+ from share_btn import (share_js)
10
+ from utils import (
11
+ get_file_as_string,
12
+ get_sections,
13
+ get_url_from_env_or_default_path,
14
+ preview
15
+ )
16
+ from constants import (
17
+ DEFAULT_STARCODER_API_PATH,
18
+ DEFAULT_STARCODER_BASE_API_PATH,
19
+ FIM_MIDDLE,
20
+ FIM_PREFIX,
21
+ FIM_SUFFIX,
22
+ END_OF_TEXT,
23
+ MIN_TEMPERATURE,
24
+ )
25
 
26
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
27
+ # Gracefully exit the app if the HF_TOKEN is not set,
28
+ # printing to system `errout` the error (instead of raising an exception)
29
+ # and the expected behavior
30
+ if not HF_TOKEN:
31
+ ERR_MSG = """
32
+ Please set the HF_TOKEN environment variable with your Hugging Face API token.
33
+ You can get one by signing up at https://huggingface.co/join and then visiting
34
+ https://huggingface.co/settings/tokens."""
35
+ print(ERR_MSG, file=sys.stderr)
36
+ # gr.errors.GradioError(ERR_MSG)
37
+ # gr.close_all(verbose=False)
38
+ sys.exit(1)
39
+
40
+ API_URL = get_url_from_env_or_default_path("STARCODER_API", DEFAULT_STARCODER_API_PATH)
41
+ API_URL_BASE = get_url_from_env_or_default_path("STARCODER_BASE_API", DEFAULT_STARCODER_BASE_API_PATH)
42
+
43
+ preview("StarCoder Model's URL", API_URL)
44
+ preview("StarCoderBase Model's URL", API_URL_BASE)
45
+ preview("HF Token", HF_TOKEN, ofuscate=True)
46
+
47
+ DEFAULT_PORT = 7860
48
 
49
  FIM_INDICATOR = "<FILL_HERE>"
50
 
51
+ # Loads the whole content of the formats.md file
52
+ # and stores it into the FORMATS variable
53
+ STATIC_PATH = "static"
54
+ FORMATS = get_file_as_string("formats.md", path=STATIC_PATH)
55
+ CSS = get_file_as_string("styles.css", path=STATIC_PATH)
56
+ community_icon_svg = get_file_as_string("community_icon.svg", path=STATIC_PATH)
57
+ loading_icon_svg = get_file_as_string("loading_icon.svg", path=STATIC_PATH)
 
 
 
 
 
 
 
 
 
58
 
59
+ # todo: evaluate making STATIC_PATH the default path instead of the current one
60
+ README = get_file_as_string("README.md")
 
61
 
62
+ # Slicing the different sections from the README
63
+ readme_sections = get_sections(README, "---")
64
 
65
+ manifest, description, disclaimer = readme_sections[:3]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  theme = gr.themes.Monochrome(
68
  primary_hue="indigo",
69
  secondary_hue="blue",
70
  neutral_hue="slate",
71
+ radius_size=sizes.radius_sm,
72
  font=[
73
+ gr.themes.GoogleFont("Rubik"),
74
  "ui-sans-serif",
75
  "system-ui",
76
  "sans-serif",
77
  ],
78
+ text_size=sizes.text_lg,
79
  )
80
 
81
+ HEADERS = {
82
+ "Authorization": f"Bearer {HF_TOKEN}",
83
+ }
84
+ client = Client(API_URL, headers = HEADERS)
85
+ client_base = Client(API_URL_BASE, headers = HEADERS)
86
+
87
+ def generate(prompt,
88
+ temperature = 0.9,
89
+ max_new_tokens = 256,
90
+ top_p = 0.95,
91
+ repetition_penalty = 1.0,
92
+ version = "StarCoder",
93
+ ):
94
+
95
+ temperature = min(float(temperature), MIN_TEMPERATURE)
96
  top_p = float(top_p)
 
97
 
98
  generate_kwargs = dict(
99
+ temperature = temperature,
100
+ max_new_tokens = max_new_tokens,
101
+ top_p = top_p,
102
+ repetition_penalty = repetition_penalty,
103
+ do_sample = True,
104
+ seed = 42,
105
  )
106
 
107
+ if fim_mode := FIM_INDICATOR in prompt:
 
108
  try:
109
  prefix, suffix = prompt.split(FIM_INDICATOR)
110
+ except Exception as err:
111
+ print(str(err))
112
+ raise ValueError(f"Only one {FIM_INDICATOR} allowed in prompt!") from err
113
  prompt = f"{FIM_PREFIX}{prefix}{FIM_SUFFIX}{suffix}{FIM_MIDDLE}"
114
 
115
+ model_client = client if version == "StarCoder" else client_base
116
+
117
+ stream = model_client.generate_stream(prompt, **generate_kwargs)
 
118
 
119
+ output = prefix if fim_mode else prompt
 
 
 
120
 
 
121
  for response in stream:
122
+ if response.token.text == END_OF_TEXT:
123
  if fim_mode:
124
  output += suffix
125
  else:
126
  return output
127
  else:
128
  output += response.token.text
129
+ # todo: log this value while in debug mode
130
+ # previous_token = response.token.text
131
  yield output
132
  return output
133
 
134
+ # todo: move it into the README too
135
  examples = [
136
  "X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.1)\n\n# Train a logistic regression model, predict the labels on the test set and compute the accuracy score",
137
  "// Returns every other value in the array as a new array.\nfunction everyOther(arr) {",
138
  "def alternating(list1, list2):\n results = []\n for i in range(min(len(list1), len(list2))):\n results.append(list1[i])\n results.append(list2[i])\n if len(list1) > len(list2):\n <FILL_HERE>\n else:\n results.extend(list2[i+1:])\n return results",
139
  ]
140
 
 
141
  def process_example(args):
142
  for x in generate(args):
143
  pass
144
  return x
145
 
146
 
147
+ with gr.Blocks(theme=theme, analytics_enabled=False, css=CSS) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  with gr.Column():
149
  gr.Markdown(description)
150
  with gr.Row():
 
208
  )
209
  gr.Markdown(disclaimer)
210
  with gr.Group(elem_id="share-btn-container"):
211
+ community_icon = gr.HTML(community_icon_svg, visible=True)
212
+ loading_icon = gr.HTML(loading_icon_svg, visible=True)
213
  share_button = gr.Button(
214
  "Share to community", elem_id="share-btn", visible=True
215
  )
 
228
  outputs=[output],
229
  )
230
  share_button.click(None, [], [], _js=share_js)
231
+
232
+ demo.queue(concurrency_count=16).launch(debug=True, server_port=DEFAULT_PORT)
constants.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ DEFAULT_HUGGINGFACE_MODELS_API_BASE_URL = "https://api-inference.huggingface.co/models/"
2
+ DEFAULT_STARCODER_API_PATH = "bigcode/starcoder/"
3
+ DEFAULT_STARCODER_BASE_API_PATH = "bigcode/starcoderbase/"
4
+
5
+ FIM_PREFIX = "<fim_prefix>"
6
+ FIM_MIDDLE = "<fim_middle>"
7
+ FIM_SUFFIX = "<fim_suffix>"
8
+ END_OF_TEXT = "<|endoftext|>"
9
+
10
+ MIN_TEMPERATURE = 1e-3
requirements.txt CHANGED
@@ -1,2 +1,7 @@
1
- huggingface_hub
2
- text-generation==0.4.1
 
 
 
 
 
 
1
+ # Gradio
2
+ gradio==3.28.2
3
+
4
+ # HuggingFace
5
+ huggingface_hub==0.14.1
6
+ text-generation==0.5.1
7
+ transformers==4.28.1
share_btn.py CHANGED
@@ -1,13 +1,3 @@
1
- community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
- <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
- <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
- </svg>"""
5
-
6
- loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
- style="color: #ffffff;
8
- "
9
- xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
-
11
  share_js = """async () => {
12
  async function uploadFile(file){
13
  const UPLOAD_URL = 'https://huggingface.co/uploads';
@@ -77,36 +67,9 @@ ${outputTxt}`;
77
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
78
  .join('&');
79
 
80
- window.open(`https://huggingface.co/spaces/bigcode/bigcode-playground/discussions/new?${paramsStr}`, '_blank');
81
 
82
  shareBtnEl.style.removeProperty('pointer-events');
83
  shareIconEl.style.removeProperty('display');
84
  loadingIconEl.style.display = 'none';
85
  }"""
86
-
87
- share_btn_css = """
88
- a {text-decoration-line: underline; font-weight: 600;}
89
- .animate-spin {
90
- animation: spin 1s linear infinite;
91
- }
92
- @keyframes spin {
93
- from { transform: rotate(0deg); }
94
- to { transform: rotate(360deg); }
95
- }
96
- #share-btn-container {
97
- display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
98
- }
99
- #share-btn {
100
- all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
101
- }
102
- #share-btn * {
103
- all: unset;
104
- }
105
- #share-btn-container div:nth-child(-n+2){
106
- width: auto !important;
107
- min-height: 0px !important;
108
- }
109
- #share-btn-container .wrap {
110
- display: none !important;
111
- }
112
- """
 
 
 
 
 
 
 
 
 
 
 
1
  share_js = """async () => {
2
  async function uploadFile(file){
3
  const UPLOAD_URL = 'https://huggingface.co/uploads';
 
67
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
68
  .join('&');
69
 
70
+ window.open(`https://huggingface.co/spaces/Fisharp/starcoder-playground/discussions/new?${paramsStr}`, '_blank');
71
 
72
  shareBtnEl.style.removeProperty('pointer-events');
73
  shareIconEl.style.removeProperty('display');
74
  loadingIconEl.style.display = 'none';
75
  }"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/community_icon.svg ADDED
static/formats.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Model Formats
2
+
3
+ The model is pretrained on code and is formatted with special tokens in addition to the pure code data,\
4
+ such as prefixes specifying the source of the file or tokens separating code from a commit message.\
5
+ Use these templates to explore the model's capacities:
6
+
7
+ ### 1. Prefixes 🏷️
8
+
9
+ For pure code files, use any combination of the following prefixes:
10
+
11
+ ```
12
+ <reponame>REPONAME<filename>FILENAME<gh_stars>STARS\ncode<|endoftext|>
13
+ ```
14
+
15
+ STARS can be one of: 0, 1-10, 10-100, 100-1000, 1000+
16
+
17
+ ### 2. Commits 💾
18
+
19
+ The commits data is formatted as follows:
20
+
21
+ ```
22
+ <commit_before>code<commit_msg>text<commit_after>code<|endoftext|>
23
+ ```
24
+
25
+ ### 3. Jupyter Notebooks 📓
26
+
27
+ The model is trained on Jupyter notebooks as Python scripts and structured formats like:
28
+
29
+ ```
30
+ <start_jupyter><jupyter_text>text<jupyter_code>code<jupyter_output>output<jupyter_text>
31
+ ```
32
+
33
+ ### 4. Issues 🐛
34
+
35
+ We also trained on GitHub issues using the following formatting:
36
+
37
+ ```
38
+ <issue_start><issue_comment>text<issue_comment>...<issue_closed>
39
+ ```
40
+
41
+ ### 5. Fill-in-the-middle 🧩
42
+
43
+ Fill in the middle requires rearranging the model inputs. The playground handles this for you - all you need is to specify where to fill:
44
+
45
+ ```
46
+ code before<FILL_HERE>code after
47
+ ```
static/loading_icon.svg ADDED
static/share_btn.js ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ async () => {
2
+ async function uploadFile(file) {
3
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
4
+ const response = await fetch(UPLOAD_URL, {
5
+ method: 'POST',
6
+ headers: {
7
+ 'Content-Type': file.type,
8
+ 'X-Requested-With': 'XMLHttpRequest',
9
+ },
10
+ body: file, /// <- File inherits from Blob
11
+ });
12
+ const url = await response.text();
13
+ return url;
14
+ }
15
+
16
+ async function getInputImgFile(imgEl) {
17
+ const res = await fetch(imgEl.src);
18
+ const blob = await res.blob();
19
+ const imgId = Date.now() % 200;
20
+ const isPng = imgEl.src.startsWith(`data:image/png`);
21
+ if (isPng) {
22
+ const fileName = `sd-perception-${{ imgId }}.png`;
23
+ return new File([blob], fileName, { type: 'image/png' });
24
+ } else {
25
+ const fileName = `sd-perception-${{ imgId }}.jpg`;
26
+ return new File([blob], fileName, { type: 'image/jpeg' });
27
+ }
28
+ }
29
+
30
+ // const gradioEl = document.querySelector('body > gradio-app');
31
+ const gradioEl = document.querySelector("gradio-app");
32
+ const inputTxt = gradioEl.querySelector('#q-input textarea').value;
33
+ let outputTxt = gradioEl.querySelector('#q-output .codemirror-wrapper .cm-scroller > div:nth-of-type(2)').innerText;
34
+ outputTxt = `<pre>${outputTxt}</pre>`
35
+
36
+ const titleLength = 150;
37
+ let titleTxt = inputTxt;
38
+ if (titleTxt.length > titleLength) {
39
+ titleTxt = titleTxt.slice(0, titleLength) + ' ...';
40
+ }
41
+
42
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
43
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
44
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
45
+
46
+ if (!inputTxt || !outputTxt) {
47
+ return;
48
+ };
49
+
50
+ shareBtnEl.style.pointerEvents = 'none';
51
+ shareIconEl.style.display = 'none';
52
+ loadingIconEl.style.removeProperty('display');
53
+
54
+ const descriptionMd = `### Question:
55
+ ${inputTxt}
56
+
57
+ ### Answer:
58
+
59
+ ${outputTxt}`;
60
+
61
+ const params = {
62
+ title: titleTxt,
63
+ description: descriptionMd,
64
+ };
65
+
66
+ const paramsStr = Object.entries(params)
67
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
68
+ .join('&');
69
+
70
+ window.open(`https://huggingface.co/spaces/Fisharp/starcoder-playground/discussions/new?${paramsStr}`, '_blank');
71
+
72
+ shareBtnEl.style.removeProperty('pointer-events');
73
+ shareIconEl.style.removeProperty('display');
74
+ loadingIconEl.style.display = 'none';
75
+ }
static/styles.css ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .generating {
2
+ visibility: hidden
3
+ }
4
+
5
+ .gradio-container {
6
+ color: black
7
+ }
8
+
9
+ /* monospace_css */
10
+ #q-input textarea {
11
+ font-family: monospace, 'Consolas', Courier, monospace;
12
+ }
13
+
14
+ /* Share Button */
15
+
16
+ /* it was hidden directly inside the svg xml content */
17
+ #share-btn-loading-icon {
18
+ display: none;
19
+ }
20
+
21
+ a {
22
+ text-decoration-line: underline;
23
+ font-weight: 600;
24
+ }
25
+
26
+ .animate-spin {
27
+ animation: spin 1s linear infinite;
28
+ }
29
+
30
+ @keyframes spin {
31
+ from {
32
+ transform: rotate(0deg);
33
+ }
34
+ to {
35
+ transform: rotate(360deg);
36
+ }
37
+ }
38
+
39
+ #share-btn-container {
40
+ display: flex;
41
+ padding-left: 0.5rem !important;
42
+ padding-right: 0.5rem !important;
43
+ background-color: #000000;
44
+ justify-content: center;
45
+ align-items: center;
46
+ border-radius: 9999px !important;
47
+ width: 13rem;
48
+ }
49
+
50
+ #share-btn {
51
+ all: initial;
52
+ color: #ffffff;
53
+ font-weight: 600;
54
+ cursor: pointer;
55
+ font-family: 'IBM Plex Sans', sans-serif;
56
+ margin-left: 0.5rem !important;
57
+ padding-top: 0.25rem !important;
58
+ padding-bottom: 0.25rem !important;
59
+ }
60
+
61
+ #share-btn * {
62
+ all: unset;
63
+ }
64
+
65
+ #share-btn-container div:nth-child(-n+2) {
66
+ width: auto !important;
67
+ min-height: 0px !important;
68
+ }
69
+
70
+ #share-btn-container .wrap {
71
+ display: none !important;
72
+ }
utils.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List
3
+ from urllib.parse import urljoin
4
+
5
+ from constants import DEFAULT_HUGGINGFACE_MODELS_API_BASE_URL
6
+
7
+
8
+ def masked(value: str, n_shown: int, length: int = None) -> str:
9
+ """Returns a string with the first and last n_shown characters
10
+ and the middle of the string replaced with '*'
11
+
12
+ Args:
13
+ value (str): The string to mask
14
+ n_shown (int): The number of characters to show at the beginning and end of the string
15
+ length (int, optional): The length of the string. If not given, it will be calculated as the length of the value. Defaults to None.
16
+
17
+ Returns:
18
+ str: The masked string
19
+ """
20
+ l = length or len(value)
21
+ return value[0:n_shown] + '*'*(length-2*n_shown) + value[-n_shown:]
22
+
23
+
24
+ def ofuscated(value: str) -> str:
25
+ """Returns a string with the first and last 4 characters
26
+ and the middle of the string replaced with '*'
27
+
28
+ Args:
29
+ value (str): The string to mask
30
+
31
+ Returns:
32
+ str: The masked string
33
+ """
34
+ return masked(value, 4, len(value)//2)
35
+
36
+
37
+ def preview(label:str, value: str, ofuscate=False):
38
+ """Print the variable name and its value in a nice way.
39
+ If ofuscate is True, it will ofuscate the value
40
+
41
+ Args:
42
+ variable_name (str): The name of the variable to print
43
+ ofuscate (bool, optional): If True, it will ofuscate the value. Defaults to False.
44
+ """
45
+ str_value = ofuscated(str(value)) if ofuscate else str(value)
46
+ print(f"{label} = {str_value}")
47
+
48
+ def get_url_from_env_or_default_path(env_name: str, api_path: str) -> str:
49
+ """Takes an url from the env variable (given the env name)
50
+ or combines with urljoin the default models base url
51
+ with the default path (given the path name)
52
+
53
+ Args:
54
+ env_name (str): The name of the environment variable to check
55
+ api_path (str): The default path to use if the environment variable is not set
56
+
57
+ Returns:
58
+ str: The url to use
59
+ """
60
+ return os.environ.get(env_name) or urljoin(
61
+ DEFAULT_HUGGINGFACE_MODELS_API_BASE_URL, api_path
62
+ )
63
+
64
+ def get_file_as_string(file_name, path='.') -> str:
65
+ """Loads the content of a file given its name
66
+ and returns all of its lines as a single string
67
+ if a file path is given, it will be used
68
+ instead of the current directory
69
+
70
+ Args:
71
+ file_name (_type_): The name of the file to load.
72
+ path (str, optional): The path to the file. Defaults to the current directory.
73
+
74
+ Returns:
75
+ str: The content of the file as a single string
76
+ """
77
+ with open(os.path.join(path, file_name), mode='r', encoding='UTF-8') as f:
78
+ return f.read()
79
+
80
+
81
+ def get_sections(string: str, delimiter: str) -> List[str]:
82
+ """Splits a string into sections given a delimiter
83
+
84
+ Args:
85
+ string (str): The string to split
86
+ delimiter (str): The delimiter to use
87
+
88
+ Returns:
89
+ List[str]: The list of sections
90
+ """
91
+ return [section.strip()
92
+ for section in string.split(delimiter)
93
+ if (section and not section.isspace())]