apply pre-commit
Browse filesFiles changed (14)
- README.md+1-1
- app.py+16-25
- app_allenai.py+19-25
- app_cohere.py+1-1
- app_gemini_voice.py+46-55
- app_huggingface.py+23-37
- app_lumaai.py+2-2
- app_meta.py+1-1
- app_mindsearch.py+2-2
- app_paligemma.py+31-51
- app_playai.py+3-3
- app_showui.py+1-1
- app_trellis.py+1-1
- utils.py+1-1
9 unmodified lines101112139 unmodified linesdisable_embedding: true---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference9 unmodified lines101112139 unmodified linesdisable_embedding: true---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
1234567891011121314151617181920212223242526272829303132333422 unmodified lines57585960616263646566676869707172737475from utils import get_app# Import all demosfrom app_cohere import demo as demo_coherefrom app_meta import demo as demo_metafrom app_lumaai import demo as demo_lumaaifrom app_paligemma import demo as demo_paligemmafrom app_replicate import demo as demo_replicatefrom app_huggingface import demo as demo_huggingfacefrom app_playai import demo as demo_playaifrom app_allenai import demo as demo_allenaifrom app_claude import demo as demo_claudefrom app_experimental import demo as demo_experimentalfrom app_fireworks import demo as demo_fireworksfrom app_gemini import demo as demo_geminifrom app_groq import demo as demo_groqfrom app_hyperbolic import demo as demo_hyperbolicfrom app_fal import demo as demo_falfrom app_mistral import demo as demo_mistralfrom app_nvidia import demo as demo_nvidiafrom app_openai import demo as demo_openaifrom app_perplexity import demo as demo_perplexityfrom app_qwen import demo as demo_qwenfrom app_sambanova import demo as demo_sambanovafrom app_together import demo as demo_togetherfrom app_xai import demo as demo_grokfrom app_showui import demo as demo_showuifrom app_omini import demo as demo_ominifrom app_gemini_voice import demo as demo_gemini_voice# Create mapping of providers to their demosPROVIDERS = {22 unmodified lines"Perplexity": demo_perplexity,"Experimental": demo_experimental,"Mistral": demo_mistral,"NVIDIA": demo_nvidia}demo = get_app(models=list(PROVIDERS.keys()),default_model="Gemini",src=PROVIDERS,dropdown_label="Select Provider")if __name__ == "__main__":demo.queue(api_open=False,).launch(show_api=False)123456789101112131415161718192021222324252627282930313222 unmodified lines555657585960616263646566from app_allenai import demo as demo_allenaifrom app_claude import demo as demo_claude# Import all demosfrom app_cohere import demo as demo_coherefrom app_experimental import demo as demo_experimentalfrom app_fal import demo as demo_falfrom app_fireworks import demo as demo_fireworksfrom app_gemini import demo as demo_geminifrom app_gemini_voice import demo as demo_gemini_voicefrom app_groq import demo as demo_groqfrom app_huggingface import demo as demo_huggingfacefrom app_hyperbolic import demo as demo_hyperbolicfrom app_lumaai import demo as demo_lumaaifrom app_meta import demo as demo_metafrom app_mistral import demo as demo_mistralfrom app_nvidia import demo as demo_nvidiafrom app_omini import demo as demo_ominifrom app_openai import demo as demo_openaifrom app_paligemma import demo as demo_paligemmafrom app_perplexity import demo as demo_perplexityfrom app_playai import demo as demo_playaifrom app_qwen import demo as demo_qwenfrom app_replicate import demo as demo_replicatefrom app_sambanova import demo as demo_sambanovafrom app_showui import demo as demo_showuifrom app_together import demo as demo_togetherfrom app_xai import demo as demo_grokfrom utils import get_app# Create mapping of providers to their demosPROVIDERS = {22 unmodified lines"Perplexity": demo_perplexity,"Experimental": demo_experimental,"Mistral": demo_mistral,"NVIDIA": demo_nvidia,}demo = get_app(models=list(PROVIDERS.keys()), default_model="Gemini", src=PROVIDERS, dropdown_label="Select Provider")if __name__ == "__main__":demo.queue(api_open=False,).launch(show_api=False)
123456789105 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465662 unmodified lines6970717273from gradio_client import Clientimport gradio as grMODELS = {"OLMo-2-1124-13B-Instruct": "akhaliq/olmo-anychat","Llama-3.1-Tulu-3-8B": "akhaliq/allen-test"}def create_chat_fn(client):def chat(message, history):5 unmodified linestop_k=40,repetition_penalty=1.1,top_p=0.95,api_name="/chat")return responsereturn chatdef set_client_for_session(model_name, request: gr.Request):headers = {}if request and hasattr(request, 'request') and hasattr(request.request, 'headers'):x_ip_token = request.request.headers.get('x-ip-token')if x_ip_token:headers["X-IP-Token"] = x_ip_tokenreturn Client(MODELS[model_name], headers=headers)def safe_chat_fn(message, history, client):if client is None:return "Error: Client not initialized. Please refresh the page."return create_chat_fn(client)(message, history)with gr.Blocks() as demo:client = gr.State()model_dropdown = gr.Dropdown(choices=list(MODELS.keys()),value="OLMo-2-1124-13B-Instruct",label="Select Model",interactive=True)chat_interface = gr.ChatInterface(fn=safe_chat_fn,additional_inputs=[client])# Update client when model changesdef update_model(model_name, request):return set_client_for_session(model_name, request)model_dropdown.change(fn=update_model,inputs=[model_dropdown],outputs=[client],)# Initialize client on page loaddemo.load(fn=set_client_for_session,2 unmodified lines)demo = demo123456785 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061622 unmodified lines656667import gradio as grfrom gradio_client import ClientMODELS = {"OLMo-2-1124-13B-Instruct": "akhaliq/olmo-anychat", "Llama-3.1-Tulu-3-8B": "akhaliq/allen-test"}def create_chat_fn(client):def chat(message, history):5 unmodified linestop_k=40,repetition_penalty=1.1,top_p=0.95,api_name="/chat",)return responsereturn chatdef set_client_for_session(model_name, request: gr.Request):headers = {}if request and hasattr(request, "request") and hasattr(request.request, "headers"):x_ip_token = request.request.headers.get("x-ip-token")if x_ip_token:headers["X-IP-Token"] = x_ip_tokenreturn Client(MODELS[model_name], headers=headers)def safe_chat_fn(message, history, client):if client is None:return "Error: Client not initialized. Please refresh the page."return create_chat_fn(client)(message, history)with gr.Blocks() as demo:client = gr.State()model_dropdown = gr.Dropdown(choices=list(MODELS.keys()), value="OLMo-2-1124-13B-Instruct", label="Select Model", interactive=True)chat_interface = gr.ChatInterface(fn=safe_chat_fn, additional_inputs=[client])# Update client when model changesdef update_model(model_name, request):return set_client_for_session(model_name, request)model_dropdown.change(fn=update_model,inputs=[model_dropdown],outputs=[client],)# Initialize client on page loaddemo.load(fn=set_client_for_session,2 unmodified lines)demo = demo
17 unmodified lines1819202117 unmodified lines)if __name__ == "__main__":demo.launch()17 unmodified lines1819202117 unmodified lines)if __name__ == "__main__":demo.launch()
1234567891011121314151617181920212223242526272829303132333435362 unmodified lines394041424344454647484950513 unmodified lines55565758596061626364656667686970717214 unmodified lines878889909192931 unmodified line95969798991001011022 unmodified lines1051061071081091101111121136 unmodified lines1201211221231241251261275 unmodified lines1331341351361371381392 unmodified lines1421431441451461471481499 unmodified lines1591601611621631641 unmodified line166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import gradio as grfrom gradio_webrtc import WebRTC, StreamHandler, get_twilio_turn_credentialsimport websockets.sync.clientimport numpy as npimport jsonimport base64import osfrom dotenv import load_dotenvclass GeminiConfig:def __init__(self):load_dotenv()self.api_key = self._get_api_key()self.host = 'generativelanguage.googleapis.com'self.model = 'models/gemini-2.0-flash-exp'self.ws_url = f'wss://{self.host}/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key={self.api_key}'def _get_api_key(self):api_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError("GOOGLE_API_KEY not found in environment variables. Please set it in your .env file.")return api_keyclass AudioProcessor:@staticmethoddef encode_audio(data, sample_rate):encoded = base64.b64encode(data.tobytes()).decode('UTF-8')return {'realtimeInput': {'mediaChunks': [{'mimeType': f'audio/pcm;rate={sample_rate}','data': encoded,}],},}2 unmodified linesaudio_data = base64.b64decode(data)return np.frombuffer(audio_data, dtype=np.int16)class GeminiHandler(StreamHandler):def __init__(self,expected_layout="mono",output_sample_rate=24000,output_frame_size=480) -> None:super().__init__(expected_layout, output_sample_rate, output_frame_size,input_sample_rate=24000)self.config = GeminiConfig()self.ws = Noneself.all_output_data = None3 unmodified linesreturn GeminiHandler(expected_layout=self.expected_layout,output_sample_rate=self.output_sample_rate,output_frame_size=self.output_frame_size)def _initialize_websocket(self):try:self.ws = websockets.sync.client.connect(self.config.ws_url,timeout=30)initial_request = {'setup': {'model': self.config.model,}}self.ws.send(json.dumps(initial_request))14 unmodified lines_, array = framearray = array.squeeze()audio_message = self.audio_processor.encode_audio(array, self.output_sample_rate)self.ws.send(json.dumps(audio_message))except Exception as e:print(f"Error in receive: {str(e)}")if self.ws:1 unmodified lineself.ws = Nonedef _process_server_content(self, content):for part in content.get('parts', []):data = part.get('inlineData', {}).get('data', '')if data:audio_array = self.audio_processor.process_audio_response(data)if self.all_output_data is None:2 unmodified linesself.all_output_data = np.concatenate((self.all_output_data, audio_array))while self.all_output_data.shape[-1] >= self.output_frame_size:yield (self.output_sample_rate,self.all_output_data[:self.output_frame_size].reshape(1, -1))self.all_output_data = self.all_output_data[self.output_frame_size:]def generator(self):while True:6 unmodified linesmessage = self.ws.recv(timeout=5)msg = json.loads(message)if 'serverContent' in msg:content = msg['serverContent'].get('modelTurn', {})yield from self._process_server_content(content)except TimeoutError:print("Timeout waiting for server response")5 unmodified linesdef emit(self) -> tuple[int, np.ndarray] | None:if not self.ws:return Noneif not hasattr(self, '_generator'):self._generator = self.generator()try:return next(self._generator)2 unmodified linesreturn Nonedef reset(self) -> None:if hasattr(self, '_generator'):delattr(self, '_generator')self.all_output_data = Nonedef shutdown(self) -> None:9 unmodified linesprint(f"Connection check failed: {str(e)}")return Falseclass GeminiVoiceChat:def __init__(self):load_dotenv()1 unmodified linedef _create_interface(self):with gr.Blocks() as demo:gr.HTML("""<div style='text-align: center'><h1>Gemini 2.0 Voice Chat</h1><p>Speak with Gemini using real-time audio streaming</p></div>""")webrtc = WebRTC(label="Conversation",modality="audio",mode="send-receive",rtc_configuration=get_twilio_turn_credentials())webrtc.stream(GeminiHandler(),inputs=[webrtc],outputs=[webrtc],time_limit=90,concurrency_limit=10)return demodef launch(self):self.demo.launch()# Create and expose the demo instancedef demo():chat = GeminiVoiceChat()return chat.demo# This is what will be imported by app.pydemo = demo()if __name__ == "__main__":demo.launch(server_name="0.0.0.0")12345678910111213141516171819202122232425262728293031323334353637383940412 unmodified lines444546474849505152533 unmodified lines57585960616263646566676869707114 unmodified lines868788899091921 unmodified line9495969798991001012 unmodified lines1041051061071081091101116 unmodified lines1181191201211221231241255 unmodified lines1311321331341351361372 unmodified lines1401411421431441451461479 unmodified lines1571581591601611621631 unmodified line165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import base64import jsonimport osimport gradio as grimport numpy as npimport websockets.sync.clientfrom dotenv import load_dotenvfrom gradio_webrtc import StreamHandler, WebRTC, get_twilio_turn_credentialsclass GeminiConfig:def __init__(self):load_dotenv()self.api_key = self._get_api_key()self.host = "generativelanguage.googleapis.com"self.model = "models/gemini-2.0-flash-exp"self.ws_url = f"wss://{self.host}/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key={self.api_key}"def _get_api_key(self):api_key = os.getenv("GOOGLE_API_KEY")if not api_key:raise ValueError("GOOGLE_API_KEY not found in environment variables. Please set it in your .env file.")return api_keyclass AudioProcessor:@staticmethoddef encode_audio(data, sample_rate):encoded = base64.b64encode(data.tobytes()).decode("UTF-8")return {"realtimeInput": {"mediaChunks": [{"mimeType": f"audio/pcm;rate={sample_rate}","data": encoded,}],},}2 unmodified linesaudio_data = base64.b64decode(data)return np.frombuffer(audio_data, dtype=np.int16)class GeminiHandler(StreamHandler):def __init__(self, expected_layout="mono", output_sample_rate=24000, output_frame_size=480) -> None:super().__init__(expected_layout, output_sample_rate, output_frame_size, input_sample_rate=24000)self.config = GeminiConfig()self.ws = Noneself.all_output_data = None3 unmodified linesreturn GeminiHandler(expected_layout=self.expected_layout,output_sample_rate=self.output_sample_rate,output_frame_size=self.output_frame_size,)def _initialize_websocket(self):try:self.ws = websockets.sync.client.connect(self.config.ws_url, timeout=30)initial_request = {"setup": {"model": self.config.model,}}self.ws.send(json.dumps(initial_request))14 unmodified lines_, array = framearray = array.squeeze()audio_message = self.audio_processor.encode_audio(array, self.output_sample_rate)self.ws.send(json.dumps(audio_message)) # type: ignoreexcept Exception as e:print(f"Error in receive: {str(e)}")if self.ws:1 unmodified lineself.ws = Nonedef _process_server_content(self, content):for part in content.get("parts", []):data = part.get("inlineData", {}).get("data", "")if data:audio_array = self.audio_processor.process_audio_response(data)if self.all_output_data is None:2 unmodified linesself.all_output_data = np.concatenate((self.all_output_data, audio_array))while self.all_output_data.shape[-1] >= self.output_frame_size:yield (self.output_sample_rate, self.all_output_data[: self.output_frame_size].reshape(1, -1))self.all_output_data = self.all_output_data[self.output_frame_size :]def generator(self):while True:6 unmodified linesmessage = self.ws.recv(timeout=5)msg = json.loads(message)if "serverContent" in msg:content = msg["serverContent"].get("modelTurn", {})yield from self._process_server_content(content)except TimeoutError:print("Timeout waiting for server response")5 unmodified linesdef emit(self) -> tuple[int, np.ndarray] | None:if not self.ws:return Noneif not hasattr(self, "_generator"):self._generator = self.generator()try:return next(self._generator)2 unmodified linesreturn Nonedef reset(self) -> None:if hasattr(self, "_generator"):delattr(self, "_generator")self.all_output_data = Nonedef shutdown(self) -> None:9 unmodified linesprint(f"Connection check failed: {str(e)}")return Falseclass GeminiVoiceChat:def __init__(self):load_dotenv()1 unmodified linedef _create_interface(self):with gr.Blocks() as demo:gr.HTML("""<div style='text-align: center'><h1>Gemini 2.0 Voice Chat</h1><p>Speak with Gemini using real-time audio streaming</p></div>""")webrtc = WebRTC(label="Conversation",modality="audio",mode="send-receive",rtc_configuration=get_twilio_turn_credentials(),)webrtc.stream(GeminiHandler(), inputs=[webrtc], outputs=[webrtc], time_limit=90, concurrency_limit=10)return demodef launch(self):self.demo.launch()demo = GeminiVoiceChat().demoif __name__ == "__main__":demo.launch(server_name="0.0.0.0")
1234567891011121314151617181920212 unmodified lines24252627282930313233343536373839404142433 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182from gradio_client import Client, handle_fileimport gradio as grimport osMODELS = {"SmolVLM-Instruct": "akhaliq/SmolVLM-Instruct"}def create_chat_fn(client):def chat(message, history):# Extract text and files from the messagetext = message.get("text", "")files = message.get("files", [])# Handle file uploads if presentprocessed_files = [handle_file(f) for f in files]response = client.predict(message={"text": text, "files": processed_files},system_prompt="You are a helpful AI assistant.",2 unmodified linestop_k=40,repetition_penalty=1.1,top_p=0.95,api_name="/chat")return responsereturn chatdef set_client_for_session(model_name, request: gr.Request):headers = {}if request and hasattr(request, 'headers'):x_ip_token = request.headers.get('x-ip-token')if x_ip_token:headers["X-IP-Token"] = x_ip_tokenreturn Client(MODELS[model_name], headers=headers)def safe_chat_fn(message, history, client):if client is None:return "Error: Client not initialized. Please refresh the page."3 unmodified linesprint(f"Error during chat: {str(e)}")return f"Error during chat: {str(e)}"with gr.Blocks() as demo:client = gr.State()model_dropdown = gr.Dropdown(choices=list(MODELS.keys()),value="SmolVLM-Instruct",label="Select Model",interactive=True)chat_interface = gr.ChatInterface(fn=safe_chat_fn,additional_inputs=[client],multimodal=True)# Update client when model changesmodel_dropdown.change(fn=set_client_for_session,inputs=[model_dropdown],outputs=[client])# Initialize client on page loaddemo.load(fn=set_client_for_session,inputs=[gr.State("SmolVLM-Instruct")],outputs=[client])demo = demo1234567891011121314151617182 unmodified lines21222324252627282930313233343536373839404142433 unmodified lines47484950515253545556575859606162636465666768import gradio as grfrom gradio_client import Client, handle_fileMODELS = {"SmolVLM-Instruct": "akhaliq/SmolVLM-Instruct"}def create_chat_fn(client):def chat(message, history):# Extract text and files from the messagetext = message.get("text", "")files = message.get("files", [])# Handle file uploads if presentprocessed_files = [handle_file(f) for f in files]response = client.predict(message={"text": text, "files": processed_files},system_prompt="You are a helpful AI assistant.",2 unmodified linestop_k=40,repetition_penalty=1.1,top_p=0.95,api_name="/chat",)return responsereturn chatdef set_client_for_session(model_name, request: gr.Request):headers = {}if request and hasattr(request, "headers"):x_ip_token = request.headers.get("x-ip-token")if x_ip_token:headers["X-IP-Token"] = x_ip_tokenreturn Client(MODELS[model_name], headers=headers)def safe_chat_fn(message, history, client):if client is None:return "Error: Client not initialized. Please refresh the page."3 unmodified linesprint(f"Error during chat: {str(e)}")return f"Error during chat: {str(e)}"with gr.Blocks() as demo:client = gr.State()model_dropdown = gr.Dropdown(choices=list(MODELS.keys()), value="SmolVLM-Instruct", label="Select Model", interactive=True)chat_interface = gr.ChatInterface(fn=safe_chat_fn, additional_inputs=[client], multimodal=True)# Update client when model changesmodel_dropdown.change(fn=set_client_for_session, inputs=[model_dropdown], outputs=[client])# Initialize client on page loaddemo.load(fn=set_client_for_session, inputs=[gr.State("SmolVLM-Instruct")], outputs=[client])if __name__ == "__main__":demo.launch()
1 unmodified line2345671 unmodified lineimport lumaai_gradiodemo = gr.load(name='dream-machine',src=lumaai_gradio.registry,)1 unmodified line2345671 unmodified lineimport lumaai_gradiodemo = gr.load(name="dream-machine",src=lumaai_gradio.registry,)
1 unmodified line23451 unmodified linedemo = gr.load("models/meta-llama/Llama-3.3-70B-Instruct")demo = demo1 unmodified line23451 unmodified linedemo = gr.load("models/meta-llama/Llama-3.3-70B-Instruct")demo = demo
3 unmodified lines4567891011123 unmodified linesdemo = gr.load(name="internlm/MindSearch", src="spaces")# Disable API access for all functionsif hasattr(demo, 'fns'):for fn in demo.fns.values():fn.api_name = Falseif __name__ == "__main__":demo.launch()3 unmodified lines4567891011123 unmodified linesdemo = gr.load(name="internlm/MindSearch", src="spaces")# Disable API access for all functionsif hasattr(demo, "fns"):for fn in demo.fns.values():fn.api_name = Falseif __name__ == "__main__":demo.launch()
12345678910111213141516172 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798from gradio_client import Client, handle_fileimport gradio as grimport osMODELS = {"Paligemma-10B": "akhaliq/paligemma2-10b-ft-docci-448"}def create_chat_fn(client, system_prompt, temperature, max_tokens, top_k, rep_penalty, top_p):def chat(message, history):text = message.get("text", "")files = message.get("files", [])processed_files = [handle_file(f) for f in files]response = client.predict(message={"text": text, "files": processed_files},system_prompt=system_prompt,2 unmodified linestop_k=top_k,repetition_penalty=rep_penalty,top_p=top_p,api_name="/chat")return responsereturn chatdef set_client_for_session(model_name, request: gr.Request):headers = {}if request and hasattr(request, 'headers'):x_ip_token = request.headers.get('x-ip-token')if x_ip_token:headers["X-IP-Token"] = x_ip_tokenreturn Client(MODELS[model_name], headers=headers)def safe_chat_fn(message, history, client, system_prompt, temperature,max_tokens, top_k, rep_penalty, top_p):if client is None:return "Error: Client not initialized. Please refresh the page."try:return create_chat_fn(client, system_prompt, temperature,max_tokens, top_k, rep_penalty, top_p)(message, history)except Exception as e:print(f"Error during chat: {str(e)}")return f"Error during chat: {str(e)}"with gr.Blocks() as demo:client = gr.State()with gr.Accordion("Advanced Settings", open=False):system_prompt = gr.Textbox(value="You are a helpful AI assistant.",label="System Prompt")with gr.Row():temperature = gr.Slider(minimum=0.0, maximum=2.0, value=0.7,label="Temperature")top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.95,label="Top P")with gr.Row():top_k = gr.Slider(minimum=1, maximum=100, value=40, step=1,label="Top K")rep_penalty = gr.Slider(minimum=1.0, maximum=2.0, value=1.1,label="Repetition Penalty")max_tokens = gr.Slider(minimum=64, maximum=4096, value=1024, step=64,label="Max Tokens")chat_interface = gr.ChatInterface(fn=safe_chat_fn,additional_inputs=[client, system_prompt, temperature,max_tokens, top_k, rep_penalty, top_p],multimodal=True)# Initialize client on page load with default modeldemo.load(fn=set_client_for_session,inputs=[gr.State("Paligemma-10B")], # Using default modeloutputs=[client])# Move the API access check here, after demo is definedif hasattr(demo, 'fns'):for fn in demo.fns.values():fn.api_name = Falsedemo = demo1234567891011121314152 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import gradio as grfrom gradio_client import Client, handle_fileMODELS = {"Paligemma-10B": "akhaliq/paligemma2-10b-ft-docci-448"}def create_chat_fn(client, system_prompt, temperature, max_tokens, top_k, rep_penalty, top_p):def chat(message, history):text = message.get("text", "")files = message.get("files", [])processed_files = [handle_file(f) for f in files]response = client.predict(message={"text": text, "files": processed_files},system_prompt=system_prompt,2 unmodified linestop_k=top_k,repetition_penalty=rep_penalty,top_p=top_p,api_name="/chat",)return responsereturn chatdef set_client_for_session(model_name, request: gr.Request):headers = {}if request and hasattr(request, "headers"):x_ip_token = request.headers.get("x-ip-token")if x_ip_token:headers["X-IP-Token"] = x_ip_tokenreturn Client(MODELS[model_name], headers=headers)def safe_chat_fn(message, history, client, system_prompt, temperature, max_tokens, top_k, rep_penalty, top_p):if client is None:return "Error: Client not initialized. Please refresh the page."try:return create_chat_fn(client, system_prompt, temperature, max_tokens, top_k, rep_penalty, top_p)(message, history)except Exception as e:print(f"Error during chat: {str(e)}")return f"Error during chat: {str(e)}"with gr.Blocks() as demo:client = gr.State()with gr.Accordion("Advanced Settings", open=False):system_prompt = gr.Textbox(value="You are a helpful AI assistant.", label="System Prompt")with gr.Row():temperature = gr.Slider(minimum=0.0, maximum=2.0, value=0.7, label="Temperature")top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.95, label="Top P")with gr.Row():top_k = gr.Slider(minimum=1, maximum=100, value=40, step=1, label="Top K")rep_penalty = gr.Slider(minimum=1.0, maximum=2.0, value=1.1, label="Repetition Penalty")max_tokens = gr.Slider(minimum=64, maximum=4096, value=1024, step=64, label="Max Tokens")chat_interface = gr.ChatInterface(fn=safe_chat_fn,additional_inputs=[client, system_prompt, temperature, max_tokens, top_k, rep_penalty, top_p],multimodal=True,)# Initialize client on page load with default modeldemo.load(fn=set_client_for_session, inputs=[gr.State("Paligemma-10B")], outputs=[client]) # Using default model# Move the API access check here, after demo is definedif hasattr(demo, "fns"):for fn in demo.fns.values():fn.api_name = Falseif __name__ == "__main__":demo.launch()
12345678910import gradio as grimport playai_gradiodemo =gr.load(name='PlayDialog',src=playai_gradio.registry,)for fn in demo.fns.values():fn.api_name = False12345678910import gradio as grimport playai_gradiodemo = gr.load(name="PlayDialog",src=playai_gradio.registry,)for fn in demo.fns.values():fn.api_name = False
4 unmodified lines56789104 unmodified lines# Disable API access for all functionsif hasattr(demo, 'fns'):for fn in demo.fns.values():fn.api_name = False4 unmodified lines56789104 unmodified lines# Disable API access for all functionsif hasattr(demo, "fns"):for fn in demo.fns.values():fn.api_name = False
6 unmodified lines789106 unmodified lines# Disable API access for all functionsif hasattr(demo, "fns"):for fn in demo.fns.values():fn.api_name = False6 unmodified lines789106 unmodified lines# Disable API access for all functionsif hasattr(demo, "fns"):for fn in demo.fns.values():fn.api_name = False
1234from typing import Callable, Literal, Dict, Unionimport gradio as gr1234from typing import Callable, Dict, Literal, Unionimport gradio as gr
README.md+1-1
app.py+16-25
app_allenai.py+19-25
app_cohere.py+1-1
app_gemini_voice.py+46-55
app_huggingface.py+23-37
app_lumaai.py+2-2
app_meta.py+1-1
app_mindsearch.py+2-2
app_paligemma.py+31-51
app_playai.py+3-3
app_showui.py+1-1
app_trellis.py+1-1
utils.py+1-1