Download main.py from testser2/Test: direct link, hf CLI and curl.
- Browser
- Download file 3.1 kB
-
https://huggingface.co/spaces/testser2/Test/resolve/main/main.py
- Command line
-
hf download hf://spaces/testser2/Test/main.py
-
curl -L -o main.py https://huggingface.co/spaces/testser2/Test/resolve/main/main.py
3.1 kB
| from fastapi import FastAPI,Depends, HTTPException, status, Request # type: ignore | |
| from fastapi.responses import StreamingResponse # type: ignore | |
| from transformers import AutoTokenizer, AutoModelForCausalLM # type: ignore | |
| from fastapi.security import APIKeyHeader # type: ignore | |
| from pydantic import BaseModel | |
| from typing import Optional | |
| from transformers import TextStreamer # type: ignore | |
| import asyncio | |
| from threading import Thread | |
| from queue import Queue | |
| # Defining a custom streamer which inherits the Text Streamer | |
| class CustomStreamer(TextStreamer): | |
| def __init__(self, queue, tokenizer, skip_prompt, **decode_kwargs) -> None: | |
| super().__init__(tokenizer, skip_prompt, **decode_kwargs) | |
| # Queue taken as input to the class | |
| self._queue = queue | |
| self.stop_signal=None | |
| self.timeout = 1 | |
| def on_finalized_text(self, text: str, stream_end: bool = False): | |
| # Instead of printing the text, we add the text into the queue | |
| self._queue.put(text) | |
| if stream_end: | |
| # Similarly we add the stop signal also in the queue to | |
| # break the stream | |
| self._queue.put(self.stop_signal) | |
| #models | |
| model_name_en = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" | |
| tokenizer_en = AutoTokenizer.from_pretrained(model_name_en) | |
| model_en = AutoModelForCausalLM.from_pretrained(model_name_en) | |
| api_key = APIKeyHeader(name="X-API-KEY", auto_error=False) | |
| async def check_api_key(api_key: str = Depends(api_key)): | |
| # Validate the API key (replace with your validation logic) | |
| if api_key != "1234567890": | |
| raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API key") | |
| return api_key | |
| class Message(BaseModel): | |
| text: str | |
| filename: Optional[str] = None | |
| app =FastAPI() | |
| # Creating the queue | |
| streamer_queue = Queue() | |
| # Creating the streamer | |
| streamer = CustomStreamer(streamer_queue, tokenizer_en, True) | |
| # The generation process | |
| def start_generation(query): | |
| prompt = """ | |
| # You are assistant that behaves very professionally. | |
| # You will only provide the answer if you know the answer. If you do not know the answer, you will say I dont know. | |
| # ###Human: {instruction}, | |
| # ###Assistant: """.format(instruction=query) | |
| inputs = tokenizer_en([prompt], return_tensors="pt") | |
| generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=64, temperature=0.1) | |
| thread = Thread(target=model_en.generate, kwargs=generation_kwargs) | |
| thread.start() | |
| # Generation initiator and response server | |
| async def response_generator(query): | |
| start_generation(query) | |
| while True: | |
| value = streamer_queue.get() | |
| if value == None: | |
| break | |
| yield value | |
| streamer_queue.task_done() | |
| await asyncio.sleep(0.1) | |
| async def stream(query: str): | |
| print(f'Query receieved: {query}') | |
| return StreamingResponse(response_generator(query), media_type='text/event-stream') | |
| async def running(): | |
| return {"Hello": f" A simple Chatbot "} | |