Spaces:
Runtime error
Runtime error
Upload 3 files
Browse filesFiles changed (3)
- app.py+158-132
- info.mdAdded+16
- requirements.txt+4-6
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146import gradio as grimport numpy as npimport randomfrom diffusers import DiffusionPipelineimport torchdevice = "cuda" if torch.cuda.is_available() else "cpu"if torch.cuda.is_available():torch.cuda.max_memory_allocated(device=device)pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)pipe.enable_xformers_memory_efficient_attention()pipe = pipe.to(device)else:pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)pipe = pipe.to(device)MAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 1024def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):if randomize_seed:seed = random.randint(0, MAX_SEED)generator = torch.Generator().manual_seed(seed)image = pipe(prompt = prompt,negative_prompt = negative_prompt,guidance_scale = guidance_scale,num_inference_steps = num_inference_steps,width = width,height = height,generator = generator).images[0]return imageexamples = ["Astronaut in a jungle, cold color palette, muted colors, detailed, 8k","An astronaut riding a green horse","A delicious ceviche cheesecake slice",]css="""#col-container {margin: 0 auto;max-width: 520px;}"""if torch.cuda.is_available():power_device = "GPU"else:power_device = "CPU"with gr.Blocks(css=css) as demo:with gr.Column(elem_id="col-container"):gr.Markdown(f"""# Text-to-Image Gradio TemplateCurrently running on {power_device}.""")with gr.Row():prompt = gr.Text(label="Prompt",show_label=False,max_lines=1,placeholder="Enter your prompt",container=False,)run_button = gr.Button("Run", scale=0)result = gr.Image(label="Result", show_label=False)with gr.Accordion("Advanced Settings", open=False):negative_prompt = gr.Text(label="Negative prompt",max_lines=1,placeholder="Enter a negative prompt",visible=False,)seed = gr.Slider(label="Seed",minimum=0,maximum=MAX_SEED,step=1,value=0,)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)with gr.Row():width = gr.Slider(label="Width",minimum=256,maximum=MAX_IMAGE_SIZE,step=32,value=512,)height = gr.Slider(label="Height",minimum=256,maximum=MAX_IMAGE_SIZE,step=32,value=512,)with gr.Row():guidance_scale = gr.Slider(label="Guidance scale",minimum=0.0,maximum=10.0,step=0.1,value=0.0,)num_inference_steps = gr.Slider(label="Number of inference steps",minimum=1,maximum=12,step=1,value=2,)gr.Examples(examples = examples,inputs = [prompt])run_button.click(fn = infer,inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],outputs = [result])demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172### ----------------------------- ###### libraries ###### ----------------------------- ###import gradio as grimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn import metrics### ------------------------------ ###### data transformation ###### ------------------------------ #### load datasetuncleaned_data = pd.read_csv('data.csv')# remove timestamp from dataset (always first column)uncleaned_data = uncleaned_data.iloc[: , 1:]data = pd.DataFrame()# keep track of which columns are categorical and what# those columns' value mappings are# structure: {colname1: {...}, colname2: {...} }cat_value_dicts = {}final_colname = uncleaned_data.columns[len(uncleaned_data.columns) - 1]# for each column...for (colname, colval) in uncleaned_data.iteritems():# check if col is already a number; if so, add col directly# to new dataframe and skip to next columnif isinstance(colval.values[0], (np.integer, float)):data[colname] = uncleaned_data[colname].copy()continue# structure: {0: "lilac", 1: "blue", ...}new_dict = {}val = 0 # first index per columntransformed_col_vals = [] # new numeric datapoints# if not, for each item in that column...for (row, item) in enumerate(colval.values):# if item is not in this col's dict...if item not in new_dict:new_dict[item] = valval += 1# then add numerical value to transformed dataframetransformed_col_vals.append(new_dict[item])# reverse dictionary only for final col (0, 1) => (vals)if colname == final_colname:new_dict = {value : key for (key, value) in new_dict.items()}cat_value_dicts[colname] = new_dictdata[colname] = transformed_col_vals### -------------------------------- ###### model training ###### -------------------------------- #### select features and predicton; automatically selects last column as predictioncols = len(data.columns)num_features = cols - 1x = data.iloc[: , :num_features]y = data.iloc[: , num_features:]# split data into training and testing setsx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)# instantiate the model (using default parameters)model = LogisticRegression()model.fit(x_train, y_train.values.ravel())y_pred = model.predict(x_test)### -------------------------------- ###### article generation ###### -------------------------------- #### borrow file reading function from reader.pydef get_feat():feats = [abs(x) for x in model.coef_[0]]max_val = max(feats)idx = feats.index(max_val)return data.columns[idx]acc = str(round(metrics.accuracy_score(y_test, y_pred) * 100, 1)) + "%"most_imp_feat = get_feat()# info = get_article(acc, most_imp_feat)### ------------------------------- ###### interface creation ###### ------------------------------- #### predictor for generic number of featuresdef general_predictor(*args):features = []# transform categorical inputfor colname, arg in zip(data.columns, args):if (colname in cat_value_dicts):features.append(cat_value_dicts[colname][arg])else:features.append(arg)# predict single datapointnew_input = [features]result = model.predict(new_input)return cat_value_dicts[final_colname][result[0]]# add data labels to replace those lost via star-argsblock = gr.Blocks()with open('info.md') as f:with block:gr.Markdown(f.readline())gr.Markdown('Take the quiz to get a personalized recommendation using AI.')with gr.Row():with gr.Group():inputls = []for colname in data.columns:# skip last columnif colname == final_colname:continue# access categories dict if data is categorical# otherwise, just use a number inputif colname in cat_value_dicts:radio_options = list(cat_value_dicts[colname].keys())inputls.append(gr.Dropdown(radio_options, type="value", label=colname))else:# add numerical inputinputls.append(gr.Number(label=colname))gr.Markdown("<br />")submit = gr.Button("Click to see your personalized result!", variant="primary")gr.Markdown("<br />")output = gr.Textbox(label="Your recommendation:", placeholder="your recommendation will appear here")submit.click(fn=general_predictor, inputs=inputls, outputs=output)gr.Markdown("<br />")with gr.Row():with gr.Group():gr.Markdown(f"<h3>Accuracy: </h3>{acc}")with gr.Group():gr.Markdown(f"<h3>Most important feature: </h3>{most_imp_feat}")gr.Markdown("<br />")with gr.Group():gr.Markdown('''⭐ Note that model accuracy is based on the uploaded data.csv and reflects how well the AI model can give correct recommendations for <em>that dataset</em>. Model accuracy and most important feature can be helpful for understanding how the model works, but <em>should not be considered absolute facts about the real world</em>.''')with gr.Group():with open('info.md') as f:f.readline()gr.Markdown(f.read())# show the interfaceblock.launch()
12345678910111213141516# 😌 [Edit info.md - Your app's title here]
### 🧐 Problem Statement and Research Summary[add info about your problem statement and your research here!]
### 🎣 Data Collection Plan[Edit info.md - add info about what data you collected and why here!]
### 💥 Ethical Considerations (Data Privacy and Bias)* Data privacy: [Edit info.md - add info about you considered users' privacy here!]* Bias: [Edit info.md - add info about you considered bias here!]
### 👻 Our Team[Edit info.md - add info about your team members here!]
123456acceleratediffusersinvisible_watermarktorchtransformersxformers1234pip>=23.2.1pandas==1.3.4scikit-learn>=1.0.1numpy==1.21.4
app.py+158-132
info.mdAdded+16
requirements.txt+4-6