选择性重载:Gradio 应用属于 AI 应用,通常需要将 AI 模型加载到内存或连接到数据存储 (如向量数据库) 。开发过程中重启服务器将导致模型重新加载或重新连接数据库,这会在开发周期间引入不必要的延迟。为解决此问题,Gradio 引入了 if gr.NORELOAD: 代码块,你可以利用它标记不需重载的代码部分。这种做法只有在 Gradio 实现了自定义重载逻辑的情况下才可行。
uvicornhttps://www.uvicorn.org/
自动重载功能https://www.uvicorn.org/
接下来,我将展示如何利用 Gradio 的重载模式迅速开发一个 AI 应用。
构建文档分析应用
本应用将允许用户上传文档图片并提出问题,随后以自然语言形式获得答案。我们将利用免费的Hugging Face 推理 API,你可以在自己的电脑上轻松操作,无需 GPU!
Hugging Face 推理 APIhttps://hf.co/docs/huggingfacehub/guides/inference
message = "" for token in client.chat_completion(messages=[user_message], max_tokens=200, stream=True, model="HuggingFaceH4/zephyr-7b-beta"): if token.choices[0].finish_reason is not None: continue message += token.choices[0].delta.content yield message
system_message = { "role": "system", "content": """ You are a helpful assistant. You will be given a question and a set of answers along with a confidence score between 0 and 1 for each answer. You job is to turn this information into a short, coherent response.
For example: Question: "Who is being invoiced?", answer: {"answer": "John Doe", "confidence": 0.98}
You should respond with something like: With a high degree of confidence, I can say John Doe is being invoiced.
Question: "What is the invoice total?", answer: [{"answer": "154.08", "confidence": 0.75}, {"answer": "155", "confidence": 0.25}
You should respond with something like: I believe the invoice total is $154.08 but it can also be $155. """}
这是我们演示的现在情况!系统消息确实帮助保持了机器人的回答简短而不包含长的小数。
应用演示带系统消息
作为最终改进,我将在页面上添加一个 Markdown 标题:
添加一个 markdown 标题
结语
在本文中,我使用 Gradio 和 Hugging Face 推理 API 开发了一个实用的 AI 应用。从开发初期,我就不确定最终产品会是什么样子,所以能够即时重新加载 UI 和服务器逻辑让我能迅速尝试各种想法。整个应用的开发过程大约只用了一个小时!
如果您想了解此演示的完整代码,请访问这个Space 应用!
Space 应用https://hf.co/spaces/freddyaboulton/document-analyzer