Spaces:
Runtime error
Runtime error
Download app.py from rezatagi1224/testbed: direct link, hf CLI and curl.
- Browser
- Download file 2.41 kB
-
https://huggingface.co/spaces/rezatagi1224/testbed/resolve/main/app.py
- Command line
-
hf download hf://spaces/rezatagi1224/testbed/app.py
-
curl -L -o app.py https://huggingface.co/spaces/rezatagi1224/testbed/resolve/main/app.py
2.41 kB
| import os | |
| import requests | |
| import gradio as gr | |
| # 1. تنظیمات اولیه و دریافت توکن | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2" | |
| API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}" | |
| def predict(text): | |
| # بررسی وجود توکن | |
| if not HF_TOKEN: | |
| return "Error: HF_TOKEN is missing! Please add it to your Space Secrets." | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| payload = { | |
| "inputs": text, | |
| "parameters": { | |
| "max_new_tokens": 500, | |
| "return_full_text": False # برای اینکه فقط پاسخ مدل را بگیری، نه سوال را | |
| } | |
| } | |
| try: | |
| response = requests.post(API_URL, headers=headers, json=payload, timeout=30) | |
| # بررسی وضعیت پاسخ HTTP | |
| if response.status_code != 200: | |
| return f"API Error ({response.status_code}): {response.text}" | |
| result = response.json() | |
| # استخراج متن به صورت امن | |
| if isinstance(result, list) and len(result) > 0: | |
| return result[0].get("generated_text", "No text found in response.") | |
| elif isinstance(result, dict) and "error" in result: | |
| return f"Model Error: {result['error']}" | |
| else: | |
| return str(result) | |
| except requests.exceptions.Timeout: | |
| return "Error: The request timed out. The model might be loading." | |
| except Exception as e: | |
| return f"Unexpected Error: {str(e)}" | |
| # 2. تعریف ساختار رابط کاربری (Interface) | |
| # ما ابتدا آن را در یک متغیر ذخیره میکنیم | |
| demo = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Textbox(lines=2, placeholder="Type your prompt here...", label="Input"), | |
| outputs=gr.Textbox(label="AI Response"), | |
| title="Mistral AI Generator", | |
| description="Ask anything to Mistral-7B via Hugging Face Inference API" | |
| ) | |
| # 3. بخش حیاتی: اجرای استاندارد برای جلوگیری از Runtime Error | |
| if __name__ == "__main__": | |
| # استفاده از server_name="0.0.0.0" برای سازگاری با کانتینرهای Hugging Face | |
| # استفاده از show_error=True برای نمایش خطاهای احتمالی در مرورگر | |
| demo.launch(server_name="0.0.0.0", show_error=True) | |