Spaces:
Runtime error

File size: 3,095 Bytes
fff3dc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

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)

@app.get('/query-stream/')
async def stream(query: str):
    print(f'Query receieved: {query}')
    return StreamingResponse(response_generator(query), media_type='text/event-stream')

@app.get("/")
async def running():
    
    return {"Hello": f" A simple Chatbot "}