Use f-strings where possible (#3984)

* Use f-strings where possible

Semi-automated using ikamensh/flynt

* Update gradio/utils.py

* Update gradio/interface.py

* formatting

---------

Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
This commit is contained in:
Aarni Koskela 2023-04-27 23:09:50 +03:00 committed by GitHub
parent 30f4556927
commit d25226f704
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 101 additions and 129 deletions

View File

@ -29,6 +29,7 @@ No changes to highlight.
## Testing and Infrastructure Changes:
- CI: Python backend lint is only run once, by [@akx](https://github.com/akx) in [PR 3960](https://github.com/gradio-app/gradio/pull/3960)
- Format invocations and concatenations were replaced by f-strings where possible by [@akx](https://github.com/akx) in [PR 3984](https://github.com/gradio-app/gradio/pull/3984)
## Breaking Changes:

View File

@ -252,9 +252,7 @@ class Block:
api_name, [dep["api_name"] for dep in Context.root_block.dependencies]
)
if not (api_name == api_name_):
warnings.warn(
"api_name {} already exists, using {}".format(api_name, api_name_)
)
warnings.warn(f"api_name {api_name} already exists, using {api_name_}")
api_name = api_name_
if collects_event_data is None:
@ -561,7 +559,7 @@ def get_api_info(config: Dict, serialize: bool = True):
if skip_endpoint:
continue
if dependency["api_name"]:
api_info["named_endpoints"]["/" + dependency["api_name"]] = dependency_info
api_info["named_endpoints"][f"/{dependency['api_name']}"] = dependency_info
elif mode == "interface" or mode == "tabbed_interface":
pass # Skip unnamed endpoints in interface mode
else:
@ -735,13 +733,13 @@ class Blocks(BlockContext):
if block_config["id"] == id:
break
else:
raise ValueError("Cannot find block with id {}".format(id))
raise ValueError(f"Cannot find block with id {id}")
cls = component_or_layout_class(block_config["type"])
block_config["props"].pop("type", None)
block_config["props"].pop("name", None)
style = block_config["props"].pop("style", None)
if block_config["props"].get("root_url") is None and root_url:
block_config["props"]["root_url"] = root_url + "/"
block_config["props"]["root_url"] = f"{root_url}/"
# Any component has already processed its initial value, so we skip that step here
block = cls(**block_config["props"], _skip_init_processing=True)
if style and isinstance(block, components.IOComponent):
@ -825,18 +823,18 @@ class Blocks(BlockContext):
def __repr__(self):
num_backend_fns = len([d for d in self.dependencies if d["backend_fn"]])
repr = f"Gradio Blocks instance: {num_backend_fns} backend functions"
repr += "\n" + "-" * len(repr)
repr += f"\n{'-' * len(repr)}"
for d, dependency in enumerate(self.dependencies):
if dependency["backend_fn"]:
repr += f"\nfn_index={d}"
repr += "\n inputs:"
for input_id in dependency["inputs"]:
block = self.blocks[input_id]
repr += "\n |-{}".format(str(block))
repr += f"\n |-{block}"
repr += "\n outputs:"
for output_id in dependency["outputs"]:
block = self.blocks[output_id]
repr += "\n |-{}".format(str(block))
repr += f"\n |-{block}"
return repr
def render(self):
@ -862,9 +860,7 @@ class Blocks(BlockContext):
)
if not (api_name == api_name_):
warnings.warn(
"api_name {} already exists, using {}".format(
api_name, api_name_
)
f"api_name {api_name} already exists, using {api_name_}"
)
dependency["api_name"] = api_name_
dependency["cancels"] = [
@ -1924,10 +1920,10 @@ Received outputs:
analytics_integration = "CometML"
comet_ml.log_other("Created from", "Gradio")
if self.share_url is not None:
comet_ml.log_text("gradio: " + self.share_url)
comet_ml.log_text(f"gradio: {self.share_url}")
comet_ml.end()
elif self.local_url:
comet_ml.log_text("gradio: " + self.local_url)
comet_ml.log_text(f"gradio: {self.local_url}")
comet_ml.end()
else:
raise ValueError("Please run `launch()` first.")
@ -1975,7 +1971,7 @@ Received outputs:
# happen the next time the app is launched
self.app.startup_events_triggered = False
if verbose:
print("Closing server running on port: {}".format(self.server_port))
print(f"Closing server running on port: {self.server_port}")
except (AttributeError, OSError): # can't close if not running
pass

View File

@ -317,7 +317,7 @@ class IOComponent(Component):
if file_name:
file_name = client_utils.strip_invalid_filename_characters(file_name)
elif guess_extension:
file_name = "file." + guess_extension
file_name = f"file.{guess_extension}"
else:
file_name = "file"
f = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
@ -1168,9 +1168,7 @@ class CheckboxGroup(
return [self.choices.index(choice) for choice in x]
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'value', 'index'."
f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
)
def postprocess(self, y: List[str] | str | None) -> List[str]:
@ -1357,9 +1355,7 @@ class Radio(
return self.choices.index(x)
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'value', 'index'."
f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
)
def get_interpretation_neighbors(self, x):
@ -1567,9 +1563,7 @@ class Dropdown(
return self.choices.index(x) if x in self.choices else None
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'value', 'index'."
f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
)
def set_interpret_parameters(self):
@ -1758,7 +1752,7 @@ class Image(
elif self.type == "filepath":
file_obj = tempfile.NamedTemporaryFile(
delete=False,
suffix=("." + fmt.lower() if fmt is not None else ".png"),
suffix=(f".{fmt.lower()}" if fmt is not None else ".png"),
)
im.save(file_obj.name)
return self.make_temp_copy_if_needed(file_obj.name)
@ -3032,9 +3026,9 @@ class Dataframe(Changeable, Selectable, IOComponent, JSONSerializable):
def __validate_headers(headers: List[str] | None, col_count: int):
if headers is not None and len(headers) != col_count:
raise ValueError(
"The length of the headers list must be equal to the col_count int.\nThe column count is set to {cols} but `headers` has {headers} items. Check the values passed to `col_count` and `headers`.".format(
cols=col_count, headers=len(headers)
)
f"The length of the headers list must be equal to the col_count int.\n"
f"The column count is set to {col_count} but `headers` has {len(headers)} items. "
f"Check the values passed to `col_count` and `headers`."
)
@classmethod
@ -3707,7 +3701,7 @@ class Label(Changeable, Selectable, IOComponent, JSONSerializable):
raise ValueError(
"The `Label` output interface expects one of: a string label, or an int label, a "
"float label, or a dictionary whose keys are labels and values are confidences. "
"Instead, got a {}".format(type(y))
f"Instead, got a {type(y)}"
)
@staticmethod

View File

@ -93,9 +93,9 @@ def load_blocks_from_repo(
"models": from_model,
"spaces": from_spaces,
}
assert src.lower() in factory_methods, "parameter: src must be one of {}".format(
factory_methods.keys()
)
assert (
src.lower() in factory_methods
), f"parameter: src must be one of {factory_methods.keys()}"
if api_key is not None:
if Context.hf_token is not None and Context.hf_token != api_key:
@ -135,9 +135,9 @@ def chatbot_postprocess(response):
def from_model(model_name: str, api_key: str | None, alias: str | None, **kwargs):
model_url = "https://huggingface.co/{}".format(model_name)
api_url = "https://api-inference.huggingface.co/models/{}".format(model_name)
print("Fetching model from: {}".format(model_url))
model_url = f"https://huggingface.co/{model_name}"
api_url = f"https://api-inference.huggingface.co/models/{model_name}"
print(f"Fetching model from: {model_url}")
headers = {"Authorization": f"Bearer {api_key}"} if api_key is not None else {}
@ -345,7 +345,7 @@ def from_model(model_name: str, api_key: str | None, alias: str | None, **kwargs
}
if p is None or p not in pipelines:
raise ValueError("Unsupported pipeline type: {}".format(p))
raise ValueError(f"Unsupported pipeline type: {p}")
pipeline = pipelines[p]
@ -406,9 +406,9 @@ def from_model(model_name: str, api_key: str | None, alias: str | None, **kwargs
def from_spaces(
space_name: str, api_key: str | None, alias: str | None, **kwargs
) -> Blocks:
space_url = "https://huggingface.co/spaces/{}".format(space_name)
space_url = f"https://huggingface.co/spaces/{space_name}"
print("Fetching Space from: {}".format(space_url))
print(f"Fetching Space from: {space_url}")
headers = {}
if api_key is not None:
@ -435,7 +435,7 @@ def from_spaces(
try:
config = json.loads(result.group(1)) # type: ignore
except AttributeError:
raise ValueError("Could not load the Space: {}".format(space_name))
raise ValueError(f"Could not load the Space: {space_name}")
if "allow_flagging" in config: # Create an Interface for Gradio 2.x Spaces
return from_spaces_interface(
space_name, config, alias, api_key, iframe_url, **kwargs
@ -467,7 +467,7 @@ def from_spaces_interface(
) -> Interface:
config = streamline_spaces_interface(config)
api_url = "{}/api/predict/".format(iframe_url)
api_url = f"{iframe_url}/api/predict/"
headers = {"Content-Type": "application/json"}
if api_key is not None:
headers["Authorization"] = f"Bearer {api_key}"

View File

@ -108,7 +108,7 @@ def encode_to_base64(r: requests.Response) -> str:
# Case 3: the data prefix is included in the response headers
else:
pass
new_base64 = "data:{};base64,".format(content_type) + base64_repr
new_base64 = f"data:{content_type};base64,{base64_repr}"
return new_base64

View File

@ -53,11 +53,11 @@ def _get_dataset_features_info(is_new, components):
"_type": "Value",
}
if isinstance(component, tuple(file_preview_types)):
headers.append(component.label + " file")
headers.append(f"{component.label} file")
for _component, _type in file_preview_types.items():
if isinstance(component, _component):
infos["flagged"]["features"][
(component.label or "") + " file"
f"{component.label or ''} file"
] = {"_type": _type}
break
@ -349,7 +349,7 @@ class HuggingFaceDatasetSaver(FlaggingCallback):
csv_data.append(filepath)
if isinstance(component, tuple(file_preview_types)):
csv_data.append(
"{}/resolve/main/{}".format(self.path_to_dataset_repo, filepath)
f"{self.path_to_dataset_repo}/resolve/main/{filepath}"
)
csv_data.append(flag_option)
writer.writerow(utils.sanitize_list_for_csv(csv_data))
@ -360,7 +360,7 @@ class HuggingFaceDatasetSaver(FlaggingCallback):
with open(self.log_file, "r", encoding="utf-8") as csvfile:
line_count = len([None for row in csv.reader(csvfile)]) - 1
self.repo.push_to_hub(commit_message="Flagged sample #{}".format(line_count))
self.repo.push_to_hub(commit_message=f"Flagged sample #{line_count}")
return line_count
@ -497,12 +497,10 @@ class HuggingFaceDatasetJSONSaver(FlaggingCallback):
filepath = None
if isinstance(component, tuple(file_preview_types)):
headers.append(component.label or "" + " file")
headers.append(f"{component.label or ''} file")
csv_data.append(
"{}/resolve/main/{}/{}".format(
self.path_to_dataset_repo, unique_name, filepath
)
f"{self.path_to_dataset_repo}/resolve/main/{unique_name}/{filepath}"
if filepath is not None
else None
)
@ -520,7 +518,7 @@ class HuggingFaceDatasetJSONSaver(FlaggingCallback):
if is_new:
json.dump(infos, open(self.infos_file, "w"))
self.repo.push_to_hub(commit_message="Flagged sample {}".format(unique_name))
self.repo.push_to_hub(commit_message=f"Flagged sample {unique_name}")
return unique_name
def get_unique_name(self):
@ -555,7 +553,7 @@ class FlagMethod:
try:
self.flagging_callback.flag(list(flag_data), flag_option=self.value)
except Exception as e:
print("Error while flagging: {}".format(e))
print(f"Error while flagging: {e}")
if self.visual_feedback:
return "Error!"
if not self.visual_feedback:

View File

@ -144,7 +144,7 @@ class Examples:
elif isinstance(examples, str):
if not Path(examples).exists():
raise FileNotFoundError(
"Could not find examples directory: " + examples
f"Could not find examples directory: {examples}"
)
working_directory = examples
if not (Path(examples) / LOG_FILE).exists():
@ -737,7 +737,7 @@ def make_waveform(
mix_pcts = [x / (n - 1) for x in range(n)]
rgb_colors = [((1 - mix) * c1_rgb + (mix * c2_rgb)) for mix in mix_pcts]
return [
"#" + "".join([format(int(round(val * 255)), "02x") for val in item])
"#" + "".join(f"{int(round(val * 255)):02x}" for val in item)
for item in rgb_colors
]

View File

@ -385,7 +385,7 @@ class Interface(Blocks):
if len(self.output_components) == 1:
component.label = "output"
else:
component.label = "output " + str(i)
component.label = f"output {i}"
if self.allow_flagging != "never":
if (
@ -461,9 +461,7 @@ class Interface(Blocks):
def render_title_description(self) -> None:
if self.title:
Markdown(
"<h1 style='text-align: center; margin-bottom: 1rem'>"
+ self.title
+ "</h1>"
f"<h1 style='text-align: center; margin-bottom: 1rem'>{self.title}</h1>"
)
if self.description:
Markdown(self.description)
@ -785,13 +783,13 @@ class Interface(Blocks):
def __repr__(self):
repr = f"Gradio Interface for: {self.__name__}"
repr += "\n" + "-" * len(repr)
repr += f"\n{'-' * len(repr)}"
repr += "\ninputs:"
for component in self.input_components:
repr += "\n|-{}".format(str(component))
repr += f"\n|-{component}"
repr += "\noutputs:"
for component in self.output_components:
repr += "\n|-{}".format(str(component))
repr += f"\n|-{component}"
return repr
async def interpret_func(self, *args):
@ -850,13 +848,11 @@ class TabbedInterface(Blocks):
css=css,
)
if tab_names is None:
tab_names = ["Tab {}".format(i) for i in range(len(interface_list))]
tab_names = [f"Tab {i}" for i in range(len(interface_list))]
with self:
if title:
Markdown(
"<h1 style='text-align: center; margin-bottom: 1rem'>"
+ title
+ "</h1>"
f"<h1 style='text-align: center; margin-bottom: 1rem'>{title}</h1>"
)
with Tabs():
for (interface, tab_name) in zip(interface_list, tab_names):

View File

@ -196,9 +196,7 @@ async def run_interpret(interface: Interface, raw_input: List):
input_component = interface.input_components[i]
if not isinstance(input_component, TokenInterpretable):
raise ValueError(
"Input component {} does not support `shap` interpretation".format(
input_component
)
f"Input component {input_component} does not support `shap` interpretation"
)
tokens, _, masks = input_component.tokenize(x)
@ -247,7 +245,7 @@ async def run_interpret(interface: Interface, raw_input: List):
scores.append(None)
alternative_outputs.append([])
else:
raise ValueError("Unknown intepretation method: {}".format(interp))
raise ValueError(f"Unknown intepretation method: {interp}")
return scores, alternative_outputs
elif interface.interpretation: # custom interpretation function
processed_input = [
@ -297,9 +295,7 @@ def quantify_difference_in_label(
else:
raise ValueError(
"This interpretation method doesn't support the Output component: {}".format(
output_component
)
f"This interpretation method doesn't support the Output component: {output_component}"
)
@ -328,7 +324,5 @@ def get_regression_or_classification_value(
else:
raise ValueError(
"This interpretation method doesn't support the Output component: {}".format(
output_component
)
f"This interpretation method doesn't support the Output component: {output_component}"
)

View File

@ -62,9 +62,7 @@ def get_first_available_port(initial: int, final: int) -> int:
except OSError:
pass
raise OSError(
"All ports from {} to {} are in use. Please close a port.".format(
initial, final - 1
)
f"All ports from {initial} to {final - 1} are in use. Please close a port."
)
@ -121,9 +119,7 @@ def start_server(
s.close()
except OSError:
raise OSError(
"Port {} is in use. If a gradio.Blocks is running on the port, you can close() it or gradio.close_all().".format(
server_port
)
f"Port {server_port} is in use. If a gradio.Blocks is running on the port, you can close() it or gradio.close_all()."
)
port = server_port
@ -134,9 +130,9 @@ def start_server(
raise ValueError(
"ssl_certfile must be provided if ssl_keyfile is provided."
)
path_to_local_server = "https://{}:{}/".format(url_host_name, port)
path_to_local_server = f"https://{url_host_name}:{port}/"
else:
path_to_local_server = "http://{}:{}/".format(url_host_name, port)
path_to_local_server = f"http://{url_host_name}:{port}/"
# Strip IPv6 brackets from the address if they exist.
# This is needed as http://[::1]:port/ is a valid browser address,

View File

@ -160,7 +160,7 @@ def load_from_pipeline(pipeline: pipelines.base.Pipeline) -> Dict:
},
}
else:
raise ValueError("Unsupported pipeline type: {}".format(type(pipeline)))
raise ValueError(f"Unsupported pipeline type: {type(pipeline)}")
# define the function that will be called by the Interface
def fn(*params):

View File

@ -55,5 +55,5 @@ def run_in_reload_mode():
message += ","
message += f" '{abs_parent}'"
print(message + "\n")
print(f"{message}\n")
os.system(command)

View File

@ -92,7 +92,7 @@ class ThemeClass:
+ "\n}"
)
return css_code + "\n" + dark_css_code
return f"{css_code}\n{dark_css_code}"
def to_dict(self):
"""Convert the theme into a python dictionary."""
@ -367,7 +367,7 @@ class Base(ThemeClass):
raise ValueError(f"Color shortcut {shortcut} not found.")
elif mode == "size":
for size in sizes.Size.all:
if size.name == prefix + "_" + shortcut:
if size.name == f"{prefix}_{shortcut}":
return size
raise ValueError(f"Size shortcut {shortcut} not found.")

View File

@ -28,7 +28,7 @@ class Tunnel:
# Check if the file exist
binary_name = f"frpc_{platform.system().lower()}_{machine.lower()}"
binary_path = str(Path(__file__).parent / binary_name) + f"_v{VERSION}"
binary_path = f"{Path(__file__).parent / binary_name}_v{VERSION}"
extension = ".exe" if os.name == "nt" else ""

View File

@ -74,11 +74,8 @@ def version_check():
]
if StrictVersion(latest_pkg_version) > StrictVersion(current_pkg_version):
print(
"IMPORTANT: You are using gradio version {}, "
"however version {} "
"is available, please upgrade.".format(
current_pkg_version, latest_pkg_version
)
f"IMPORTANT: You are using gradio version {current_pkg_version}, "
f"however version {latest_pkg_version} is available, please upgrade."
)
print("--------")
except json.decoder.JSONDecodeError:
@ -110,7 +107,7 @@ def initiated_analytics(data: Dict[str, Any]) -> None:
def initiated_analytics_thread(data: Dict[str, Any]) -> None:
try:
requests.post(
analytics_url + "gradio-initiated-analytics/", data=data, timeout=5
f"{analytics_url}gradio-initiated-analytics/", data=data, timeout=5
)
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
pass # do not push analytics if no network
@ -124,7 +121,7 @@ def launch_analytics(data: Dict[str, Any]) -> None:
def launch_analytics_thread(data: Dict[str, Any]) -> None:
try:
requests.post(
analytics_url + "gradio-launched-analytics/", data=data, timeout=5
f"{analytics_url}gradio-launched-analytics/", data=data, timeout=5
)
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
pass # do not push analytics if no network
@ -183,7 +180,7 @@ def launched_telemetry(blocks: gradio.Blocks, data: Dict[str, Any]) -> None:
def launched_telemtry_thread(data: Dict[str, Any]) -> None:
try:
requests.post(
analytics_url + "gradio-launched-telemetry/", data=data, timeout=5
f"{analytics_url}gradio-launched-telemetry/", data=data, timeout=5
)
except Exception:
pass
@ -197,7 +194,7 @@ def integration_analytics(data: Dict[str, Any]) -> None:
def integration_analytics_thread(data: Dict[str, Any]) -> None:
try:
requests.post(
analytics_url + "gradio-integration-analytics/", data=data, timeout=5
f"{analytics_url}gradio-integration-analytics/", data=data, timeout=5
)
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
pass # do not push analytics if no network
@ -216,7 +213,7 @@ def error_analytics(message: str) -> None:
def error_analytics_thread(data: Dict[str, Any]) -> None:
try:
requests.post(
analytics_url + "gradio-error-analytics/", data=data, timeout=5
f"{analytics_url}gradio-error-analytics/", data=data, timeout=5
)
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
pass # do not push analytics if no network
@ -229,7 +226,7 @@ async def log_feature_analytics(feature: str) -> None:
async with aiohttp.ClientSession() as session:
try:
async with session.post(
analytics_url + "gradio-feature-analytics/", data=data
f"{analytics_url}gradio-feature-analytics/", data=data
):
pass
except (aiohttp.ClientError):
@ -736,7 +733,7 @@ def sanitize_value_for_csv(value: str | Number) -> str | Number:
if any(value.startswith(prefix) for prefix in unsafe_prefixes) or any(
sequence in value for sequence in unsafe_sequences
):
value = "'" + value
value = f"'{value}"
return value
@ -763,10 +760,10 @@ def append_unique_suffix(name: str, list_of_names: List[str]):
return name
else:
suffix_counter = 1
new_name = name + f"_{suffix_counter}"
new_name = f"{name}_{suffix_counter}"
while new_name in set_of_names:
suffix_counter += 1
new_name = name + f"_{suffix_counter}"
new_name = f"{name}_{suffix_counter}"
return new_name
@ -907,7 +904,7 @@ def tex2svg(formula, *args):
DPI = 300
plt.rc("mathtext", fontset="cm")
fig = plt.figure(figsize=(0.01, 0.01))
fig.text(0, 0, r"${}$".format(formula), fontsize=FONTSIZE)
fig.text(0, 0, rf"${formula}$", fontsize=FONTSIZE)
output = BytesIO()
fig.savefig(
output,

View File

@ -151,7 +151,7 @@ class TestBlocksMethods:
def test_partial_fn_in_config(self):
def greet(name, formatter):
return formatter("Hello " + name + "!")
return formatter(f"Hello {name}!")
greet_upper_case = partial(greet, formatter=capwords)
with gr.Blocks() as demo:
@ -626,7 +626,7 @@ class TestCallFunction:
text = gr.Textbox()
btn = gr.Button()
btn.click(
lambda x: "Hello, " + x,
lambda x: f"Hello, {x}",
inputs=text,
outputs=text,
)
@ -646,12 +646,12 @@ class TestCallFunction:
text2 = gr.Textbox()
btn = gr.Button()
btn.click(
lambda x: "Hello, " + x,
lambda x: f"Hello, {x}",
inputs=text,
outputs=text,
)
text.change(
lambda x: "Hi, " + x,
lambda x: f"Hi, {x}",
inputs=text,
outputs=text2,
)
@ -786,7 +786,7 @@ class TestBatchProcessing:
def batch_fn(x):
results = []
for word in x:
results.append("Hello " + word)
results.append(f"Hello {word}")
return (results,)
with gr.Blocks() as demo:
@ -847,7 +847,7 @@ class TestBatchProcessing:
def batch_fn(x):
results = []
for word in x:
results.append("Hello " + word)
results.append(f"Hello {word}")
yield (results,)
with gr.Blocks() as demo:
@ -864,7 +864,7 @@ class TestBatchProcessing:
def batch_fn(x):
results = []
for word in x:
results.append("Hello " + word)
results.append(f"Hello {word}")
return (results,)
with gr.Blocks() as demo:
@ -883,7 +883,7 @@ class TestBatchProcessing:
def batch_fn(x, y):
results = []
for word1, word2 in zip(x, y):
results.append("Hello " + word1 + word2)
results.append(f"Hello {word1}{word2}")
return (results,)
with gr.Blocks() as demo:

View File

@ -1927,7 +1927,7 @@ class TestHTML:
"""
def bold_text(text):
return "<strong>" + text + "</strong>"
return f"<strong>{text}</strong>"
iface = gr.Interface(bold_text, "text", "html")
assert iface("test") == "<strong>test</strong>"

View File

@ -116,7 +116,7 @@ class TestProcessExamples:
@pytest.mark.asyncio
async def test_caching(self):
io = gr.Interface(
lambda x: "Hello " + x,
lambda x: f"Hello {x}",
"text",
"text",
examples=[["World"], ["Dunya"], ["Monde"]],
@ -335,7 +335,7 @@ class TestProcessExamples:
def test_end_to_end_cache_examples(self):
def concatenate(str1, str2):
return str1 + " " + str2
return f"{str1} {str2}"
io = gr.Interface(
concatenate,

View File

@ -52,7 +52,7 @@ class TestInterface:
def test_partial_functions(self):
def greet(name, formatter):
return formatter("Hello " + name + "!")
return formatter(f"Hello {name}!")
greet_upper_case = partial(greet, formatter=capwords)
demo = Interface(fn=greet_upper_case, inputs="text", outputs="text")

View File

@ -17,8 +17,8 @@ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
class TestSeries:
def test_in_interface(self):
io1 = gr.Interface(lambda x: x + " World", "textbox", gr.Textbox())
io2 = gr.Interface(lambda x: x + "!", "textbox", gr.Textbox())
io1 = gr.Interface(lambda x: f"{x} World", "textbox", gr.Textbox())
io2 = gr.Interface(lambda x: f"{x}!", "textbox", gr.Textbox())
series = mix.Series(io1, io2)
assert series("Hello") == "Hello World!"
@ -36,8 +36,8 @@ class TestSeries:
class TestParallel:
def test_in_interface(self):
io1 = gr.Interface(lambda x: x + " World 1!", "textbox", gr.Textbox())
io2 = gr.Interface(lambda x: x + " World 2!", "textbox", gr.Textbox())
io1 = gr.Interface(lambda x: f"{x} World 1!", "textbox", gr.Textbox())
io2 = gr.Interface(lambda x: f"{x} World 2!", "textbox", gr.Textbox())
parallel = mix.Parallel(io1, io2)
assert parallel("Hello") == ["Hello World 1!", "Hello World 2!"]
@ -45,7 +45,7 @@ class TestParallel:
io1 = gr.Interface(
lambda x: (x, x + x), "textbox", [gr.Textbox(), gr.Textbox()]
)
io2 = gr.Interface(lambda x: x + " World 2!", "textbox", gr.Textbox())
io2 = gr.Interface(lambda x: f"{x} World 2!", "textbox", gr.Textbox())
parallel = mix.Parallel(io1, io2)
assert parallel("Hello") == [
"Hello",

View File

@ -77,8 +77,8 @@ class TestRoutes:
with Blocks() as demo:
i = Textbox()
o = Textbox()
i.change(lambda x: x + "1", i, o, api_name="p")
i.change(lambda x: x + "2", i, o, api_name="q")
i.change(lambda x: f"{x}1", i, o, api_name="p")
i.change(lambda x: f"{x}2", i, o, api_name="q")
app, _, _ = demo.launch(prevent_thread_lock=True)
client = TestClient(app)
@ -96,8 +96,8 @@ class TestRoutes:
with Blocks() as demo:
i = Textbox()
o = Textbox()
i.change(lambda x: x + "0", i, o, api_name="p")
i.change(lambda x: x + "1", i, o, api_name="p")
i.change(lambda x: f"{x}0", i, o, api_name="p")
i.change(lambda x: f"{x}1", i, o, api_name="p")
app, _, _ = demo.launch(prevent_thread_lock=True)
client = TestClient(app)
@ -115,9 +115,9 @@ class TestRoutes:
with Blocks() as demo:
i = Textbox()
o = Textbox()
i.change(lambda x: x + "0", i, o, api_name="p")
i.change(lambda x: x + "1", i, o, api_name="p")
i.change(lambda x: x + "2", i, o, api_name="p_1")
i.change(lambda x: f"{x}0", i, o, api_name="p")
i.change(lambda x: f"{x}1", i, o, api_name="p")
i.change(lambda x: f"{x}2", i, o, api_name="p_1")
app, _, _ = demo.launch(prevent_thread_lock=True)
client = TestClient(app)
@ -146,7 +146,7 @@ class TestRoutes:
def batch_fn(x):
results = []
for word in x:
results.append("Hello " + word)
results.append(f"Hello {word}")
return (results,)
with gr.Blocks() as demo:

View File

@ -16,7 +16,7 @@ def build(output_dir, jinja_env, latest_gradio_stable):
template = jinja_env.get_template("index/template.html")
star_request = requests.get("https://api.github.com/repos/gradio-app/gradio").json()
star_count = (
"{:,}".format(star_request["stargazers_count"])
f"{star_request['stargazers_count']:,}"
if "stargazers_count" in star_request
else ""
)