Chapter 2. From Handler Functions to Interfaces
The text cleanup tool in Chapter 1 has an input box, a button, and a result area on its UI. Not one word in that chapter explained how these went from a C# method to a UI.
This chapter starts from the smallest application. The example is a tool that splits by a separator. A piece of text and a separator go in, multiple lines come out, empty segments are dropped, and the end reports how many segments there are in total.
It is not the cleanup tool from Chapter 1, nor is it the first module of the workbench. This chapter is about “how a handler function becomes a UI”, and a small application is the easiest way to do that; how the workbench is put together is left for Chapter 4.
2.1 Interface’s Inputs, Function, and Outputs
The whole application is about fifty lines.
using Gradio.Net;
static string Split(string text, string separator)
{
if (string.IsNullOrWhiteSpace(text))
{
return "(no input)";
}
var parts = text.Split(
string.IsNullOrEmpty(separator) ? "\n" : separator,
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 0)
{
return "(no segments to split)";
}
return string.Join("\n", parts) + $"\n\n-- {parts.Length} segments";
}
var source = gr.Textbox(
label: "Text to split",
value: "apples, bananas, oranges",
lines: 6);
var separator = gr.Textbox(
label: "Separator",
value: ",");
var result = gr.Textbox(
label: "Split result",
lines: 8,
interactive: false);
var demo = gr.Interface(
Split,
inputs: [source, separator],
outputs: [result],
title: "Split by Separator",
description: "Split a piece of text into lines by a separator, and empty segments are dropped.",
examples: new[]
{
new[] { "apples, bananas, oranges", "," },
new[] { "first;second;third", ";" },
},
submitBtn: "Split",
flaggingMode: "never",
apiName: "split");
demo.Launch();
The code divides into four parts: one handler function, three components, one gr.Interface call, and one Launch. The last part is left for 2.5; look at the first three first.
The handler function is Split. It takes two strings and returns a string, and not one line in it is there for the UI framework to see. No HTTP, no HTML, and no idea whether a browser or something else is calling it. This division of labor is the foundation of the whole chapter: logic belongs to the function, the UI belongs to the components. Swap Split for any other function and the UI structure need not change; write the UI another way and the function need not change either. The more than twenty chapters that follow come back to this again and again. Modules in the workbench are swapped in and out, but the handler functions stay the same handler functions.
All three components are Textbox, but their position differs, and so does their role. The first two go into inputs, the last into outputs.
The components in inputs become the handler function’s parameters in order. source is first, and its current value is fed to text; separator is second, and its value is fed to separator. Order is the contract, and a contract that never reports an error. Swap the positions of these two Textboxes in inputs and Split still receives two strings, it compiles, it runs, only the results are all wrong. It treats the separator as the text to split. There is no hint for this kind of error; you just have to remember the order yourself.
The components in outputs receive the return values in order. Split returns one string, result is the only output component, and that string becomes the content of the result box. If the handler function needs to return two values, you need two output components, one for each; Chapter 3 expands on this.
Figure 2-1 The correspondence between Interface’s inputs, handler function, and outputs
What happens behind one click goes through four steps in order. The browser sends the current values of the two input boxes; the framework puts them into the parameter list in the order of inputs; Split is called; the returned string is written into result. Not one line of code here is written by you. No building a request, no serialization, and no logic to push the result back into the page. All you write is “what goes in, what comes out, and what is computed in between”.
This division of labor has another practical benefit: the handler function can be used on its own, away from the UI. Chapter 1 put the cleanup rules into a class library that does not reference Gradio.NET, and both the console version and the web version reference it — that is the extreme version of the same idea. This chapter’s Split is not extracted because it is too short; once the function in your hands grows past a hundred lines, or needs to be reused in two places, you should move it into a class library the way Chapter 1 did, leaving only a few lines of wiring code in the UI layer.
Launch this chapter’s sample with the three commands from the preface, and open 127.0.0.1:7860 in the browser.
Figure 2-2 The sample’s initial UI
The two input boxes already have content; that is the initial value given by the components’ value. The result area on the right is empty.
This is easy to misunderstand. The initial value is only filled into the input box; when the page opens it does not run the handler function once for you. Many people using it for the first time think a result should appear on the right first, then go looking for what they wrote wrong. Nothing is wrong; it simply does not run. To see a result, click the button.
Change the text to “red; green; blue; yellow”, the separator to “;”, and click “Split”.
Figure 2-3 After clicking “Split”
Four lines of results, with the last line being the segment count. That is all you can control on the UI: two input boxes, a submit button, and a result area. Below there are also the clear button and the examples table, covered in 2.3 and 2.4.
A few parameters in the code are still unexplained. title and description are the two lines of text at the top of the page; examples is the examples table below; submitBtn is the text on the button; flaggingMode turns off the “Flag” button that would otherwise appear by default; and apiName is completely invisible on the page.
These parameters fall into two groups by what they affect. One group decides what happens after you click; the other decides what extra things appear on the page. The first group is the focus of this chapter, covered in 2.3 and 2.4; the second group is title, description, the button text, the examples table, and the Flag button that appears by default — they change what the page looks like, not the result that gets computed. The discussion below follows this split instead of listing parameters. Listing them once is not something you will remember; you would have to come back and look them up when you use them.
apiName belongs to neither group, so let us get it out of the way first. It decides what this function is called when invoked as an interface. Given split, the interface is /split; without it, the library takes the handler function’s name, and this chapter’s handler function is written in top-level statements as a local function, so it cannot get a decent name and the endpoint becomes /lambda. What /gradio_api/info lists is /lambda. Only by switching to a static method TextOps.Split does the endpoint become /Split. That is why the sample writes apiName explicitly. You cannot see it in the browser; it only affects how the outside world calls this application, and Chapter 22 will make use of it.
2.2 Choosing Input and Output Components for the Handler Function
Why are all three components Textbox? Because all three of these things are text on the page.
When choosing a component, first look at what form it should take on the page. A piece of text, a number, a set of options, a table, a file — each has its own component. Decide what this value looks like on the UI first, then go find the matching one in the component family, and you usually get it right in one step. Do it the other way around — pick a component that looks nice first, then figure out how to cram the data in — and you always end up doing conversions somewhere, and the more conversions, the more room for error.
Following this line of thinking: a piece of text is Textbox, a number is Number, a set of options is Radio or Dropdown, a table is Dataframe, a file is File. What parameters each of these components has and where its boundaries lie are covered one by one starting in Chapter 6; this chapter only needs Textbox.
The three values in this chapter are all text, all use Textbox, but they are used differently and their parameters differ too.
The difference between an input component and an output component is not in the component itself, but in which side it is placed on. In the sample all three components are Textbox, the first two went into inputs and the last into outputs; move result into inputs and it becomes an ordinary input box. The same component can be both read and written; its position decides whether this time it feeds data or receives a result. Components placed in outputs are non-editable by default; to make one editable you have to write interactive: true explicitly.
label is for people to read. It appears above the input box and also in the header of the examples table. The handler function cannot see it. Split only knows it received two strings; it does not know what they are called.
value is the initial value, that is, the content pre-filled in the box when the page opens. The first two components both give one. The text cell is “apples, bananas, oranges”, the separator is “,”. The result box has none, because it should be empty the moment it opens; filling in an initial result would only make people think it was computed. The benefit of filling in an initial value is that the page is clickable as soon as it opens, with no need to think about what to type first.
lines decides how tall the box is, measured in lines. The text to split is given 6 lines, the separator is given the default 1 line. Because a separator is only one or two characters, giving it 6 lines would just waste screen space. This parameter only affects appearance, not what the handler function receives.
interactive decides whether this cell can be changed. Input boxes need not write it; they are editable by default. The result box is already non-editable in Interface — you cannot click into it or type in it. The interactive: false written in the sample only makes this fact explicit; it is not the reason it takes effect. To actually make an output editable you have to write interactive: true explicitly, which Chapter 3 will use.
Why is the result box disabled? Because it displays the handler function’s return value, not an input. Let people edit it and the edited content is not sent back, it is overwritten on the next run, and it only makes them think the edit took effect. Every output component that “only displays” should have interaction turned off.
As for what type Textbox passes to the handler function, this chapter gives the answer up front: string. It has other forms too (password box, length limit, submit on Enter), covered one by one in Chapter 6. How the component’s parameters match the handler function’s parameter types, and what happens when they do not, is treated systematically in Chapter 3.
Besides label, there is one more name worth getting right while you are at it: the handler function’s parameter names. They do not appear on the UI, but they do appear in the interface documentation. In this chapter’s /gradio_api/info, the parameter_name of the two parameters are text and separator, matching Split’s parameter names. What people see is label; what callers see is the parameter name — do not use names like a or b in either place.
The order of decisions is: first fix the types of the inputs and outputs, then fix the number and order of the components, and only then tune the components’ detailed parameters. Reverse that order and you will spend your time tuning a component you chose wrong.
2.3 Initial Values and Examples
Initial values were covered in the previous section. Whatever you put in value is what is in the box when the page opens. It takes effect only at that one moment.
examples are ready-made inputs prepared for the user. The form is one group per row, with the values in each row arranged in the order of inputs, one value per input.
examples: new[]
{
new[] { "apples, bananas, oranges", "," },
new[] { "first;second;third", ";" },
},
Two examples render as a table on the UI, whose header is the components’ label (the block below Figure 2-2). The table has two rows and two columns; the first column is “Text to split”, the second is “Separator”.
Examples have two uses. One is convenience: the user does not have to think up what to type, picking a row gives ready-made values. The other is documentation: putting two examples there is tantamount to telling people what kind of input this tool accepts, and that the separator can be a comma or a semicolon. The second use is often underestimated. Once a tool is in other people’s hands, the person writing the instructions is usually you, and an examples table is less work than a paragraph of explanation and less likely to go out of date.
Click any cell in an example row.
Figure 2-4 After clicking the second example
Both input boxes change together. The text to split becomes “first;second;third”, the separator becomes “;” — exactly the values of those two cells in the second row. Columns and inputs line up by order. The first column goes to the first input, the second column to the second input, the same rule as “order is the contract” in 2.1. The examples table is not just decoration; one click fills in the form.
The result area does not move along with it. Examples do only one thing, “filling in values”; they do not click the button for you. What the result of that row is, you have to find out by clicking “Split” yourself. This is the same behavior as the initial values. Filling in values is one thing, running the function is another. Click the second row and then click “Split”, and the right side shows “first / second / third” plus a line “. 3 segments”, which matches the group you filled in by hand.
One more detail is easy to miss. You click one cell, but the whole row is filled in. That cell is only the entry point; the values are distributed to each input by column. And precisely because it fills the page rather than the configuration, pressing F5 to refresh returns both boxes to their initial values.
2.4 Submit, Stop, and Clear Buttons
There are places for three buttons on the UI. Clear is on the left, Submit on the right, and the stop button is normally invisible (Figure 2-2 shows only the first two).
submitBtn is the text on the submit button. Without it, it defaults to Submit; this chapter’s sample gives “Split” instead. The wording is worth choosing carefully: writing an action (Split, Clean up, Convert) is better than writing “Submit”. Users read the button text before they click, and a word that names an action reassures them more than a generic one does.
clearBtn is the clear button; its default text is Clear. It does two things: it clears all input boxes and it clears all output boxes. There is one point that is easy to misremember: clearing is not restoring the initial values. This chapter’s sample has initial values “apples, bananas, oranges” and “,”; click Clear and both boxes are empty, not back to those two rows of initial values. The initial values are used only once, when the page loads; clearing is just clearing.
There is one thing about clearBtn that is easy to misunderstand. Passing null means adopting the default Clear, so visible is still true. To change the text, give a string; to make it not show, pass ButtonSpec.None, and that button’s visible becomes false.
stopBtn is the stop button, drawn only when the handler function returns a stream. This chapter’s Split returns a single string all at once, not a stream, so even if you give stopBtn some text, no stop button appears on the page.
The stop button solves a different kind of problem: the handler function takes tens of seconds to run and the user wants to give up halfway. A function that returns all at once has no “halfway” to speak of; once clicked you can only wait for it to finish. So not having it now does not affect anything.
timeLimit is a parameter in the same direction. It sets a time limit for streaming runs, 30 seconds by default. This chapter’s handler function is not streaming, so changing this value makes no observable difference on the UI. Both the stop button and the time limit only become meaningful in Chapter 16, when streaming output is covered.
There is one more button that appears by default, Flag. It marks a particular input/output pair and stores it as a record. This chapter’s sample turns it off with flaggingMode: "never". This tool has no samples that need manual marking; leaving it there only invites misclicks. If you do not write this parameter, the page gets this extra button.
Of the three buttons, only submit is required. The stop button exists only when there is a stream; the clear button can be hidden — passing ButtonSpec.None keeps the button from being generated, and it is harmless to most tools anyway. Just do not expect it to restore the boxes to their initial values. The basis for the decision is still that old question: what does the person using it want to do next.
2.5 Launch Parameters and Port Conflicts
demo.Launch() has four parameters you can write, and this line writes none of them.
demo.Launch(
serverName: "127.0.0.1",
serverPort: 7860,
preventThreadLock: false,
quiet: false);
The values in the block above are exactly the defaults; they are written out only to make clear what is available. Of the four parameters, the first two decide “where to listen”, and the last two decide “how to wait” and “whether to speak”.
serverName defaults to 127.0.0.1, which means only the local machine can connect. Change it to another address and you expose the application on another network interface, so people on the same network segment can open it too. That is beyond the scope of this book; the three limitations in Chapter 1 make it clear that it is for personal use on the local machine only. So none of this book’s samples change it.
serverPort defaults to 7860, the port in the browser’s address. The preface covered how to change the port and how to troubleshoot when the port is occupied; here we only cover what you can see from the application’s side.
When the port is occupied, launch another instance of the same application and the second process outputs this:
System.IO.IOException: Failed to bind to address http://127.0.0.1:7860: address already in use.
Then the whole process exits, ending as an uncaught exception, with exit code -532462766 (that is, 0xE0434352 in hexadecimal, the fixed code for an unhandled exception in a .NET process). The first application is unaffected and keeps serving normally.
Let us break this behavior down.
It does not switch ports automatically. If the port is taken, startup fails; it does not fall back and try 7861, 7862, and so on. This is a good thing. The address is something the user keeps in a bookmark; silently changing it is worse than failing.
It does not just warn and keep running. Failure is failure: the process exits and the page cannot open. So when you see the browser cannot connect, the first thing to do is check the console, not refresh the page.
It affects only the new process. The old one is still there, holding the port and continuing to serve. This also explains the most common scenario: you forgot to close the application from your last run, so the new startup fails, the UI still shows the old one, and the new code never ran even once.
What holds 7860 is usually an instance from your last run that you did not close, or a debug session still hanging in the IDE. The preface gives troubleshooting steps for who is holding it and whether to touch it, so they are not repeated here.
One habit that saves a lot of time: run only one instance at a time, and when startup fails, look at the first line of the console rather than refreshing the browser first. The browser only tells you it cannot connect; the console tells you why.
quiet defaults to false: on startup it prints that one line with the address, plus a few lines of ASP.NET startup logs. Set it to true and the console shows not a single word. It does not just turn off the address line; the startup logs go too, and the output file is 0 bytes. So it suits the case where “you know it is running and do not want to see logs”, not first-time debugging. When something goes wrong, you cannot even tell whether it came up.
preventThreadLock defaults to false, meaning Launch blocks until the process is stopped (Ctrl+C). Set it to true and Launch returns a server object immediately, and the code after it keeps going. There is one thing to know first. The service runs inside this process; once the program ends, the service ends with it. So it suits being hosted by another host. In that scenario the process is managed by another layer’s lifecycle, which Chapter 21 will use; written as the last line of top-level statements it is meaningless.
There is also an implicit convention: one listening address per process. To run two applications at the same time you need two processes and two ports.
2.6 Where Interface Applies
Interface fixes the layout: inputs on the left, outputs on the right, a row of buttons below, and the examples table below that. You cannot change this structure; all you can change is the content, the text, and a few switches.
This structure maps to one model: fill in a form, submit, see the result. One loop, run once, done.
This model covers more scenarios than you might think. This chapter’s splitting is one; Chapter 1’s text cleanup is one; formatting a piece of JSON, computing a summary over a batch of data, or resizing an image are all examples. What they share is one operation, one result, and inputs and outputs that all fit on one screen.
Cases outside the boundary are easy to recognize too. If any of the following appears, Interface cannot express it.
If one page needs to hold two unrelated operations, Interface cannot lay them out. It has only one submit button and can run only one function at a time.
If you need to save the previous result so that two operations are related, there is no place to store it here.
If you need sections, collapsing, pagination, or two operations triggering each other, Interface does not even have the vocabulary to express these.
These belong respectively to Blocks in Chapter 4, events in Chapter 5, state in Chapter 14, and layout in Chapter 18.
But that does not make this chapter a transitional one. The value of Interface is that it lays out three things most clearly: which component feeds which parameter, which return value lands in which component, and what happens when the button is clicked. These three still hold under a different way of organizing things, only then you have to write them out yourself. Understand them first, then look at freer layouts, and you will not mix “UI” and “logic” together.
The dividing line falls on the number of loops. With only one loop, Interface’s three elements match up one to one; when a second loop appears, or two loops need to affect each other, it is time to switch to Blocks. It has only one submit button and cannot store the previous result either.
2.7 Chapter Summary
The three elements of Interface are inputs, function, and outputs. The components in inputs become the handler function’s parameters in order, and the components in outputs receive the return values in order. A wrong order does not report an error, it only computes wrong, so treat the order as a contract to remember.
Initial values are only filled into the input boxes; they do not automatically run once when the page opens. Clicking an example row fills that row’s values into each input box by column, and does not run the function either. What examples save is typing, not clicking the button.
Of the three buttons, only submit is required. The stop button appears only for streaming handler functions, and the clear button clears inputs and outputs together without returning to the initial values.
Launch has four parameters: listening address, port, whether to return immediately, and whether to be quiet. When the port is occupied it reports an error and exits; it does not switch ports automatically, nor does it just warn and keep running.
Interface fits the single “fill in a form, submit, see the result” loop. When a second loop appears, it is time to switch to a different way of organizing things.
The next chapter covers the contract between components and handler functions: what type a component passes to the handler function, what the handler function should accept and return, and what happens when they do not match.