import datetime import random import os import re from io import StringIO import gradio as gr import pandas as pd from huggingface_hub import Repository, upload_file from text_generation import Client from share_btn import (community_icon_html, loading_icon_html, share_btn_css, share_js) HF_TOKEN = os.environ.get("HF_TOKEN", None) API_TOKEN = os.environ.get("API_TOKEN", HF_TOKEN) DIALOGUES_DATASET = "ArmelR/gradio_playground_dialogues" API_URL_G = "https://api-inference.huggingface.co/models/ArmelR/starcoder-gradio-v0" API_URL_S = "https://api-inference.huggingface.co/models/HuggingFaceH4/starcoderbase-finetuned-oasst1" API_URL_B = "https://api-inference.huggingface.co/models/HuggingFaceH4/starchat-beta" model2endpoint = { "starChat-alpha": API_URL_S, "starCoder-gradio": API_URL_G, "starChat-beta": API_URL_B } model_names = list(model2endpoint.keys()) with open("./HHH_prompt_short.txt", "r") as f: HHH_PROMPT = f.read() + "\n\n" with open("./TA_prompt_v0.txt", "r") as f: TA_PROMPT = f.read() NO_PROMPT = "" def randomize_seed_generator(): seed = random.randint(0, 1000000) return seed def save_inputs_and_outputs(now, inputs, outputs, generate_kwargs, model): buffer = StringIO() timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f") file_name = f"prompts_{timestamp}.jsonl" data = {"model": model, "inputs": inputs, "outputs": outputs, "generate_kwargs": generate_kwargs} pd.DataFrame([data]).to_json(buffer, orient="records", lines=True) # Push to Hub upload_file( path_in_repo=f"{now.date()}/{now.hour}/{file_name}", path_or_fileobj=buffer.getvalue().encode(), repo_id=DIALOGUES_DATASET, token=HF_TOKEN, repo_type="dataset", ) # Clean and rerun buffer.close() def get_total_inputs(inputs, chatbot, preprompt, user_name, assistant_name, sep): past = [] for data in chatbot: user_data, model_data = data if not user_data.startswith(user_name): user_data = user_name + user_data if not model_data.startswith(sep + assistant_name): model_data = sep + assistant_name + model_data past.append(user_data + model_data.rstrip() + sep) if not inputs.startswith(user_name): inputs = user_name + inputs total_inputs = preprompt + "".join(past) + inputs + sep + assistant_name.rstrip() return total_inputs def wrap_html_code(text): pattern = r"<.*?>" matches = re.findall(pattern, text) if len(matches) > 0: return f"```{text}```" else: return text def has_no_history(chatbot, history): return not chatbot and not history def get_inference_prompt(messages, model_name): if model_name == "starChat-beta" : prompt = "<|system|>\n<|endoftext|>\n" for message in messages : if message["role"] == "user" : prompt += f"<|user|>\n{message['content']}<|endoftext|>\n<|assistant|>" else : # message["role"] == "assistant" prompt += f"\n{message['content']}<|endoftext|>\n" elif model_name == "starChat-alpha" : prompt = "<|system|>\n<|end|>\n" for message in messages : if message["role"] == "user" : prompt += f"<|user|>\n{message['content']}<|end|>\n<|assistant|>" else : # message["role"] == "assistant" prompt += f"\n{message['content']}<|end|>\n" else : # starCoder-gradio prompt = "" for message in messages : if message["role"] == "user" : prompt += f"Question: {message['content']}\n\nAnswer:" else : # message["role"] == "assistant" prompt += f" {message['content']}\n\n" return prompt def generate( RETRY_FLAG, model_name, system_message, user_message, chatbot, history, temperature, top_k, top_p, max_new_tokens, repetition_penalty, do_save=True, ): client = Client( model2endpoint[model_name], headers={"Authorization": f"Bearer {API_TOKEN}"}, timeout=60, ) # Don't return meaningless message when the input is empty if not user_message: print("Empty input") if not RETRY_FLAG: history.append(user_message) seed = 42 else: seed = randomize_seed_generator() past_messages = [] for data in chatbot: user_data, model_data = data past_messages.extend( [{"role": "user", "content": user_data}, {"role": "assistant", "content": model_data.rstrip()}] ) if len(past_messages) < 1: prompt = get_inference_prompt(messages=[{"role": "user", "content": user_message}], model_name=model_name) else: prompt = get_inference_prompt(messages=past_messages + [{"role": "user", "content": user_message}], model_name=model_name) generate_kwargs = { "temperature": temperature, "top_k": top_k, "top_p": top_p, "max_new_tokens": max_new_tokens, } temperature = float(temperature) if temperature < 1e-2: temperature = 1e-2 top_p = float(top_p) generate_kwargs = dict( temperature=temperature, max_new_tokens=max_new_tokens, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True, truncate=4096, seed=seed, stop_sequences=["<|end|>", "Question:"], ) stream = client.generate_stream( prompt, **generate_kwargs, ) output = "" for idx, response in enumerate(stream): if response.token.special: continue output += response.token.text if idx == 0: history.append(" " + output) else: history[-1] = output chat = [ (wrap_html_code(history[i].strip()), wrap_html_code(history[i + 1].strip())) for i in range(0, len(history) - 1, 2) ] # chat = [(history[i].strip(), history[i + 1].strip()) for i in range(0, len(history) - 1, 2)] yield chat, history, user_message, "" if HF_TOKEN and do_save: try: now = datetime.datetime.now() current_time = now.strftime("%Y-%m-%d %H:%M:%S") print(f"[{current_time}] Pushing prompt and completion to the Hub") save_inputs_and_outputs(now, prompt, output, generate_kwargs, model_name) except Exception as e: print(e) return chat, history, user_message, "" examples = [ """How to upload dataframe with content of file upload? I did not find any documentation of this. I want to upload a CSV file, display the data in an interactive table and then us the table conents to create a plot. But I am stuck with gluing the components together. import gradio as gr default_csv = "Phase,Activity,Start date,End date\n\"Mapping the Field\",\"Literature review\",2024-01-01,2024-01-31" def process_csv_text(text): df = pd.read_csv(StringIO(text), parse_dates=["Start date", "End date"]) return df with gr.Blocks() as demo: upload_button = gr.UploadButton(label="Upload Timetable", file_types = ['.csv'], live=True, file_count = "single") table = gr.Dataframe(headers=["Phase", "Activity", "Start date", "End date"], col_count=4, default=process_csv_text(default_csv)) image = gr.Plot() upload_button.click(fn=process_csv_text, inputs=upload_button, outputs=table, api_name="upload_csv") demo.launch() """, """Hi, I want to remove the "clear" button in Gradio Interface. Is there a way to do such a thing?""", """Why the botton can not apply css? But textbox works great. import gradio as gr import numpy as np css = \""" #warning {background-color: #FFCCCB} .feedback textarea {font-size: 64px !important} \""" with gr.Blocks(css=css) as demo: box1 = gr.Button(value="Good Job", elem_classes="feedback") box2 = gr.Textbox(value="Failure", elem_id="warning", elem_classes="feedback") if __name__ == "__main__": demo.launch(inbrowser=True) """, """ I'm very new to both huggingface and Gradio, so forgive me if this is a trivial issue, and I'm just a fool. I'm using a Blocks object to implement a very basic chatbot, and I'd like to essentially clear the input textbox after the user presses enter or presses the submit button. with gr.Blocks() as test: outp = gr.Chatbot(label="Reply", ) inp = gr.Textbox(label="Chat with AI") inp.submit(chatbot, [outp, inp], outp) inp.update(lambda: None, inp) btn = gr.Button("Submit") btn.click(fn=chatbot, inputs=inp, outputs=outp) My code looks like this currently. I simply wish to clear the input textbox after the input is submitted. """, """ I am trying to force Gradio to show a white background colour ALL the time in all browsers. My code below works to force white colour on my desktop (using Firefox) but on mobile it's still showing the typical default Gradio black background. How to change this behaviour to permanently show a white background in all devices? Thank you ```python demo = gr.Interface( lambda x:x+x, inputs=gr.Textbox(label='Test'), outputs=gr.Textbox(label='test2'), css=".gradio-container {background-color: white} " ).launch(share=False) ``` """, """ I am using gradio. I'm creating some tabs and when i click a button i want to use the name of the tabs as an input for a function. How does it work? Thank you very much! My way of creating tabs would be for example this, with blocks: ```python with gr.Tabs() as tabs: with gr.TabItem("test1"): bt_test1 = gr.Button('test1') with gr.TabItem("test2"): bt_test2 = gr.Button('test2') ``` """, """ Can I change the layout when I click a button in gradio? For example, I would like to add a row or change some other layout of the frame when i click a button. how can i do this operation. """ ] def clear_chat(): return [], [] def delete_last_turn(chat, history): if chat and history: chat.pop(-1) history.pop(-1) history.pop(-1) return chat, history def process_example(args): for [x, y] in generate(args): pass return [x, y] # Regenerate response def retry_last_answer( selected_model, system_message, user_message, chat, history, temperature, top_k, top_p, max_new_tokens, repetition_penalty, do_save, ): if chat and history: # Removing the previous conversation from chat chat.pop(-1) # Removing bot response from the history history.pop(-1) # Setting up a flag to capture a retry RETRY_FLAG = True # Getting last message from user user_message = history[-1] yield from generate( RETRY_FLAG, selected_model, system_message, user_message, chat, history, temperature, top_k, top_p, max_new_tokens, repetition_penalty, do_save, ) title = """