Spaces:
Runtime error
Runtime error
Update app.py
Browse files7 unmodified lines89101112131415161718194 unmodified lines24252627282930314 unmodified lines36373839404142433 unmodified lines47484950515253543 unmodified lines5859606162636465666768697071727374757677787980811 unmodified line83848586878889909192932 unmodified lines969798991001011021031041052 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311327 unmodified linesraise ValueError("HF_TOKEN environment variable not set. Please set it before running the app.")# Initialize the client for the Coldet backend with HF_TOKEN in headerscoldet_client = Client("Coldet/backend", headers={"Authorization": f"Bearer {HF_TOKEN}"})# --- Helper Functions ---def create_account(username: str, password: str) -> str:"""Create a new account and return the session ID."""try:result = coldet_client.predict(username=username,4 unmodified linesexcept Exception as e:return f"Error: {str(e)}"def login(username: str, password: str) -> str:"""Login and return the session ID."""try:result = coldet_client.predict(username=username,4 unmodified linesexcept Exception as e:return f"Error: {str(e)}"def create_token(session_id: str) -> str:"""Generate an API key for the session."""try:result = coldet_client.predict(session_id=session_id,3 unmodified linesexcept Exception as e:return f"Error: {str(e)}"def predict(image, api_key: str, model: str = "coldet-v1-mini.coldet") -> str:"""Run inference on the provided image."""try:result = coldet_client.predict(image=handle_file(image),3 unmodified lines)return resultexcept Exception as e:return f"Error: {str(e)}"# --- Gradio Interface ---with gr.Blocks(title="Coldet Backend Interface", theme=gr.themes.Soft()) as demo:gr.Markdown("# π Coldet Backend Interface")gr.Markdown("Use this interface to interact with the Coldet backend API.")# --- Account Tab ---with gr.Tab("π Account"):gr.Markdown("### Create Account or Login")with gr.Row():with gr.Column():gr.Markdown("#### Create Account")create_username = gr.Textbox(label="Username", placeholder="Enter username")create_password = gr.Textbox(label="Password", placeholder="Enter password", type="password")create_btn = gr.Button("Create Account")create_output = gr.Textbox(label="Session ID", interactive=False)create_btn.click(fn=create_account,inputs=[create_username, create_password],1 unmodified line)with gr.Column():gr.Markdown("#### Login")login_username = gr.Textbox(label="Username", placeholder="Enter username")login_password = gr.Textbox(label="Password", placeholder="Enter password", type="password")login_btn = gr.Button("Login")login_output = gr.Textbox(label="Session ID", interactive=False)login_btn.click(fn=login,inputs=[login_username, login_password],2 unmodified lines# --- API Key Tab ---with gr.Tab("π API Key"):gr.Markdown("### Generate API Key")session_id_input = gr.Textbox(label="Session ID", placeholder="Paste your session ID here")token_btn = gr.Button("Generate API Key")token_output = gr.Textbox(label="API Key", interactive=False)token_btn.click(fn=create_token,inputs=session_id_input,2 unmodified lines# --- Inference Tab ---with gr.Tab("π€ Inference"):gr.Markdown("### Run Inference")with gr.Row():with gr.Column():image_input = gr.Image(label="Upload Image", type="filepath")api_key_input = gr.Textbox(label="API Key", placeholder="Paste your API key here")model_input = gr.Dropdown(label="Model",choices=["coldet-v1-mini.coldet"],value="coldet-v1-mini.coldet",)predict_btn = gr.Button("Run Inference")with gr.Column():predict_output = gr.JSON(label="Inference Result")predict_btn.click(fn=predict,inputs=[image_input, api_key_input, model_input],outputs=predict_output,)# Launch the appif __name__ == "__main__":demo.launch()7 unmodified lines891011121314151617181920214 unmodified lines26272829303132334 unmodified lines38394041424344453 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991003 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511 unmodified line1531541551561571581591601611621631641651661671681691701711721731741751761771781792 unmodified lines1821831841851861871881891901911921931941951961971981992002012022 unmodified lines2052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592607 unmodified linesraise ValueError("HF_TOKEN environment variable not set. Please set it before running the app.")# Initialize the client for the Coldet backend with HF_TOKEN in headerscoldet_client = Client("Coldet/backend",headers={"Authorization": f"Bearer {HF_TOKEN}"})# --- Helper Functions ---def create_account(username: str, password: str) -> str:try:result = coldet_client.predict(username=username,4 unmodified linesexcept Exception as e:return f"Error: {str(e)}"def login(username: str, password: str) -> str:try:result = coldet_client.predict(username=username,4 unmodified linesexcept Exception as e:return f"Error: {str(e)}"def create_token(session_id: str) -> str:try:result = coldet_client.predict(session_id=session_id,3 unmodified linesexcept Exception as e:return f"Error: {str(e)}"# AUTO FETCH MODELS FROM BACKEND CONFIGdef get_models():try:config = coldet_client.view_api(return_format="dict")predict_endpoint = config["named_endpoints"]["/predict"]params = predict_endpoint["parameters"]for param in params:if param.get("parameter_name") == "model":choices = param.get("python_type", "")# Extract Literal choicesif "Literal[" in choices:models = (choices.replace("Literal[", "").replace("]", "").replace("'", "").split(", "))return modelsreturn ["coldet-v1-mini.coldet"]except Exception as e:print(f"Failed to fetch models: {e}")return ["coldet-v1-mini.coldet"]AVAILABLE_MODELS = get_models()def refresh_models():global AVAILABLE_MODELSAVAILABLE_MODELS = get_models()return gr.update(choices=AVAILABLE_MODELS,value=AVAILABLE_MODELS[0] if AVAILABLE_MODELS else None,)def predict(image, api_key: str, model: str):try:result = coldet_client.predict(image=handle_file(image),3 unmodified lines)return resultexcept Exception as e:return {"error": str(e)}# --- Gradio Interface ---with gr.Blocks(title="Coldet Backend Interface",theme=gr.themes.Soft(),) as demo:gr.Markdown("# π Coldet Backend Interface")gr.Markdown("Use this interface to interact with the Coldet backend API.")# --- Account Tab ---with gr.Tab("π Account"):gr.Markdown("### Create Account or Login")with gr.Row():with gr.Column():gr.Markdown("#### Create Account")create_username = gr.Textbox(label="Username",placeholder="Enter username")create_password = gr.Textbox(label="Password",placeholder="Enter password",type="password")create_btn = gr.Button("Create Account")create_output = gr.Textbox(label="Session ID",interactive=False)create_btn.click(fn=create_account,inputs=[create_username, create_password],1 unmodified line)with gr.Column():gr.Markdown("#### Login")login_username = gr.Textbox(label="Username",placeholder="Enter username")login_password = gr.Textbox(label="Password",placeholder="Enter password",type="password")login_btn = gr.Button("Login")login_output = gr.Textbox(label="Session ID",interactive=False)login_btn.click(fn=login,inputs=[login_username, login_password],2 unmodified lines# --- API Key Tab ---with gr.Tab("π API Key"):gr.Markdown("### Generate API Key")session_id_input = gr.Textbox(label="Session ID",placeholder="Paste your session ID here")token_btn = gr.Button("Generate API Key")token_output = gr.Textbox(label="API Key",interactive=False)token_btn.click(fn=create_token,inputs=session_id_input,2 unmodified lines# --- Inference Tab ---with gr.Tab("π€ Inference"):gr.Markdown("### Run Inference")with gr.Row():with gr.Column():image_input = gr.Image(label="Upload Image",type="filepath")api_key_input = gr.Textbox(label="API Key",placeholder="Paste your API key here")model_input = gr.Dropdown(label="Model",choices=AVAILABLE_MODELS,value=AVAILABLE_MODELS[0] if AVAILABLE_MODELS else None,)refresh_btn = gr.Button("π Refresh Models")predict_btn = gr.Button("Run Inference")with gr.Column():predict_output = gr.JSON(label="Inference Result")refresh_btn.click(fn=refresh_models,outputs=model_input,)predict_btn.click(fn=predict,inputs=[image_input, api_key_input, model_input],outputs=predict_output,)# AUTO REFRESH MODELS ON PAGE LOADdemo.load(fn=refresh_models,outputs=model_input,)# Launch the appif __name__ == "__main__":demo.launch()
app.py+149-21