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etime, tempfile, safetensors, torch, threading, spaces
|
| 3 |
+
import numpy as np
|
| 4 |
+
from huggingface_hub import hf_hub_download, HfApi, upload_folder, create_repo
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
+
from accelerate import Accelerator
|
| 7 |
+
from huggingface_hub import login
|
| 8 |
+
HF_TOKEN=os.environ.get('HF_TOKEN')
|
| 9 |
+
login(token=HF_TOKEN)
|
| 10 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
| 11 |
+
os.environ["ZERO_GPU_PATCH_TORCH_DEVICE"] = "True"
|
| 12 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
+
accelerator=Accelerator()
|
| 14 |
+
HfApi=HfApi()
|
| 15 |
+
last=[]
|
| 16 |
+
thecomponent=""
|
| 17 |
+
TOKENIZER = accelerator.prepare(AutoTokenizer.from_pretrained("Qwen/Qwen2.5-Coder-7B-Instruct"))
|
| 18 |
+
MODEL = accelerator.prepare(AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-Coder-7B-Instruct", torch_dtype=torch.bfloat16,))
|
| 19 |
+
eos_token_ids = [151645, 151643]
|
| 20 |
+
|
| 21 |
+
@spaces.GPU()
|
| 22 |
+
def helper(pmpt, input_text):
|
| 23 |
+
model_inputs=""
|
| 24 |
+
generated_text=""
|
| 25 |
+
prompt = f"{pmpt}. The code: <|fim_prefix|>{input_text} <|fim_suffix|> <|fim_middle|>"
|
| 26 |
+
messages = [{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant. Acting as an expert AI Web Development and Programming model. As an expert AI Web Development and Programming model, correct/modify/create/generate/complete the user provided code based on user request, output the code without comments. Only output code without additional prefixed or suffixed messages/comments/wrapping or additional text."}, {"role": "user", "content": prompt}]
|
| 27 |
+
text = TOKENIZER.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
|
| 28 |
+
model_inputs = TOKENIZER([text], return_tensors="pt").to(device)
|
| 29 |
+
generated_text = ""
|
| 30 |
+
for new_text in TOKENIZER.decode(MODEL.generate(**model_inputs, max_new_tokens=2048, do_sample=False, eos_token_id=eos_token_ids,)[0][len(model_inputs.input_ids[0]):], skip_special_tokens=True):
|
| 31 |
+
generated_text += new_text
|
| 32 |
+
yield generated_text.strip()
|
| 33 |
+
yield generated_text.strip()
|
| 34 |
+
|
| 35 |
+
def pushy(spc_id,spc_tkn,thecomponent):
|
| 36 |
+
tm_tkn=f"{spc_tkn}"
|
| 37 |
+
succ=HfApi.create_repo(repo_id=f"{spc_id}", repo_type="space", space_sdk="gradio", private=False, exist_ok=True, token=f"{tm_tkn}")
|
| 38 |
+
HfApi.upload_folder(repo_id=f"{spc_id}",repo_type="space", folder_path=f"{thecomponent}")
|
| 39 |
+
del tm_tkn
|
| 40 |
+
shutil.rmtree(thecomponent)
|
| 41 |
+
gc.collect()
|
| 42 |
+
print("Successfully pushed custom component.")
|
| 43 |
+
return gr.Textbox(label="Step 6: Enter a new/existing space name", value=f"Success: created space {str(succ)}"), gr.Textbox(label="Your HF Token(write permission)", value="")
|
| 44 |
+
|
| 45 |
+
files_list=[]
|
| 46 |
+
def list_files(files_list,thecomponent):
|
| 47 |
+
files_list=[]
|
| 48 |
+
for root, dirs, files in os.walk(f"{os.getcwd()}/{thecomponent}", topdown=True):
|
| 49 |
+
if '.git' in dirs:
|
| 50 |
+
dirs.remove('.git')
|
| 51 |
+
if '.gitattributes' in files:
|
| 52 |
+
files.remove('.gitattributes')
|
| 53 |
+
for name in files:
|
| 54 |
+
rel_dir = os.path.relpath(root, os.getcwd())
|
| 55 |
+
rel_file = os.path.join(rel_dir, name) if rel_dir != '.' else name
|
| 56 |
+
files_list.append(rel_file)
|
| 57 |
+
print(os.path.join(root, name))
|
| 58 |
+
return files_list
|
| 59 |
+
|
| 60 |
+
def lep(thecomponent):
|
| 61 |
+
with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
|
| 62 |
+
tmpname = tmpfile.name
|
| 63 |
+
os.system(f"ls {os.getcwd()}/{thecomponent} > {tmpname} 2>&1")
|
| 64 |
+
with open(tmpname, "r") as f:
|
| 65 |
+
output = f.read()
|
| 66 |
+
os.remove(tmpname)
|
| 67 |
+
return output
|
| 68 |
+
|
| 69 |
+
def read_file(filename,cd,status):
|
| 70 |
+
fauxname=filename
|
| 71 |
+
filename=f"./{filename}"
|
| 72 |
+
with open(filename, "r", encoding="utf-8") as f:
|
| 73 |
+
return f.read(), f"Editing {fauxname}"
|
| 74 |
+
|
| 75 |
+
def write_file(filename, thecomponent, content, lstf_dp):
|
| 76 |
+
fauxname=filename
|
| 77 |
+
filename=f"./{filename}"
|
| 78 |
+
with open(filename, "w", encoding="utf-8") as f:
|
| 79 |
+
f.write(content)
|
| 80 |
+
return f"Saved {fauxname}", gr.Dropdown(choices=list_files(files_list, thecomponent), value=f"{fauxname}", type="value")
|
| 81 |
+
|
| 82 |
+
def empty(cd,crea_name,lst_fls):
|
| 83 |
+
return gr.Code(label=None, value="", interactive=True), gr.Textbox(label="Filename to create", value="", placeholder="filename.txt"), gr.Textbox(label=f"{str(os.getcwd())}",value=lep())
|
| 84 |
+
|
| 85 |
+
def open_file(selected_file,cd,status):
|
| 86 |
+
return read_file(selected_file,cd,status)
|
| 87 |
+
|
| 88 |
+
def save_file(selected_file, thecomponent, content, lstf_dp):
|
| 89 |
+
return write_file(selected_file, thecomponent, content, lstf_dp)
|
| 90 |
+
|
| 91 |
+
def refresh_files(lstf_dp,lst_fls):
|
| 92 |
+
return gr.Dropdown(choices=list_files(files_list), value=None, type="value"), gr.Textbox(label=f"{os.getcwd}",value=lep())
|
| 93 |
+
|
| 94 |
+
def run_command_os_system(cmd,fos,lstf_dp,lst_fls):
|
| 95 |
+
thecomponent=f"{cmd}"
|
| 96 |
+
cmd=f"gradio cc create {cmd} --directory {cmd} --package-name {cmd} --template {fos} --no-install --overwrite --no-configure-metadata"
|
| 97 |
+
import tempfile
|
| 98 |
+
with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
|
| 99 |
+
tmpname = tmpfile.name
|
| 100 |
+
os.system(f"{cmd} > {tmpname} 2>&1")
|
| 101 |
+
with open(tmpname, "r") as f:
|
| 102 |
+
output = f.read()
|
| 103 |
+
os.remove(tmpname)
|
| 104 |
+
return output, gr.Dropdown(label="Step 4: Select a file to modify/edit..",choices=list_files(files_list,thecomponent), value=None, type="value"), gr.Textbox(label=f"{str(os.getcwd())}/{str(thecomponent)}",value=lep(thecomponent),visible=True)
|
| 105 |
+
|
| 106 |
+
with gr.Blocks() as iface:
|
| 107 |
+
with gr.Row():
|
| 108 |
+
lstf_dp=gr.Dropdown(label="Step 4: Select a file to modify/edit..Carefully review each file.",choices=[], value=None, type="value")
|
| 109 |
+
with gr.Column():
|
| 110 |
+
with gr.Group():
|
| 111 |
+
with gr.Row():
|
| 112 |
+
pmpt=gr.Textbox(label="Prompt", placeholder="Prompt goes here... eg: Extend the code to include an option a method and necessary functions for automatic...")
|
| 113 |
+
with gr.Row():
|
| 114 |
+
sv=gr.Button("Try AI Assisted Editing", size="md")
|
| 115 |
+
with gr.Group():
|
| 116 |
+
with gr.Row():
|
| 117 |
+
status = gr.Textbox(label="Status", interactive=False, placeholder="Edit mode:")
|
| 118 |
+
with gr.Row():
|
| 119 |
+
save_btn = gr.Button("Save",size="sm")
|
| 120 |
+
with gr.Row():
|
| 121 |
+
cd=gr.Code(label="Step 5: Modify/Edit code.. Don't forget to save modifications..",interactive=True,lines=30)
|
| 122 |
+
with gr.Group():
|
| 123 |
+
with gr.Row():
|
| 124 |
+
spc_id=gr.Textbox(label="Step 6: Enter a new/existing space name", placeholder="eg: JoPmt/my_new_custom_gradio_component")
|
| 125 |
+
with gr.Row():
|
| 126 |
+
spc_tkn=gr.Textbox(label="Your HF Token(write permission)")
|
| 127 |
+
with gr.Row():
|
| 128 |
+
spc_btn=gr.Button("Push custom component to space")
|
| 129 |
+
with gr.Row():
|
| 130 |
+
bldcc=gr.Button("Optional: Build Custom Component (Must have pypi account)..wip",interactive=False)
|
| 131 |
+
sv.click(helper,[pmpt,cd],cd)
|
| 132 |
+
with gr.Sidebar(position="left", open=True):
|
| 133 |
+
with gr.Row():
|
| 134 |
+
output_os = gr.Textbox(label="System stdout:", lines=6, interactive=False, placeholder=">")
|
| 135 |
+
with gr.Row():
|
| 136 |
+
cmd_input = gr.Textbox(label="Step 1: Name your custom component",placeholder="eg: Mycomponent")
|
| 137 |
+
with gr.Row():
|
| 138 |
+
fos=gr.Dropdown(label="Step 2: Pick a template to modify", choices=["SimpleDropdown", "SimpleTextbox", "SimpleImage", "Audio", "BarPlot", "Button", "Chatbot", "ClearButton", "Checkbox", "CheckboxGroup", "Code", "ColorPicker", "DataFrame", "DownloadButton", "DuplicateButton", "Gallery", "HTML", "FileExplorer", "Image", "JSON", "Label", "LinePlot", "BrowserState", "LoginButton", "Markdown", "Textbox", "DateTime", "Dropdown", "Model3D", "File", "HighlightedText", "AnnotatedImage", "CheckboxGroup", "Number", "Plot", "Radio", "ScatterPlot", "Slider", "Timer", "UploadButton", "Video", "ImageEditor", "ImageSlider", "ParamViewer", "MultimodalTextbox", "NativePlot", "DeepLinkButton", "Accordion", "Column", "Row", "Group", "Tabs", "Tab", "TabItem", "Sidebar"],value=None,type="value")
|
| 139 |
+
with gr.Row():
|
| 140 |
+
run_os_btn = gr.Button("Step 3: Setup custom component",size="md")
|
| 141 |
+
with gr.Row():
|
| 142 |
+
lst_fls=gr.Textbox(label="",value="",visible=False)
|
| 143 |
+
with gr.Row():
|
| 144 |
+
crea_name=gr.Textbox(label="Optional: Filename to create", placeholder="eg: filename.txt")
|
| 145 |
+
with gr.Row():
|
| 146 |
+
create_fl=gr.Button("Optional: Create file",size="md")
|
| 147 |
+
lstf_dp.input(open_file, inputs=[lstf_dp,cd,status], outputs=[cd,status])
|
| 148 |
+
create_fl.click(save_file,[crea_name,cd,lstf_dp],[status,lstf_dp]).then(empty,[cd,crea_name,lst_fls],[cd,crea_name,lst_fls])##.then(refresh_files,[lstf_dp,lst_fls],[lstf_dp,lst_fls])
|
| 149 |
+
spc_btn.click(pushy,[spc_id,spc_tkn, cmd_input],[spc_id,spc_tkn]).then(fn=None,inputs=None,outputs=None,js="""()=>{window.location="";};""")
|
| 150 |
+
run_os_btn.click(run_command_os_system, inputs=[cmd_input,fos,lstf_dp,lst_fls], outputs=[output_os,lstf_dp,lst_fls])
|
| 151 |
+
iface.launch(ssr_mode=False)
|