Sachin5112 commited on
Commit
7dd2541
Β·
verified Β·
1 Parent(s): f3b8c50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -74
app.py CHANGED
@@ -5,11 +5,9 @@ from llama_cpp import Llama
5
  from huggingface_hub import hf_hub_download
6
  from fastapi import FastAPI
7
  from pydantic import BaseModel
8
- from threading import Thread, Event
9
  import uvicorn
10
 
11
- stop_event = Event()
12
-
13
  # ----------------------------
14
  # Model
15
  # ----------------------------
@@ -29,68 +27,47 @@ llm = Llama(
29
 
30
  llm("warmup", max_tokens=1)
31
 
 
 
 
32
  SYSTEM_PROMPT = """
33
  You are an advanced AI assistant.
34
  Answer questions clearly and concisely.
 
35
  """
36
 
37
  # ----------------------------
38
- # Chat function
39
  # ----------------------------
40
  def generate_response(message, history):
41
  yield "πŸ€– Thinking..."
42
- time.sleep(0.3)
 
43
  prompt = f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
44
  for h in history:
45
- if isinstance(h, dict):
46
  role = h["role"]
47
  msg = h["message"]
48
- prompt += f"<|im_start|>{role}\n{msg}<|im_end|>\n"
49
- elif isinstance(h, (list, tuple)) and len(h) == 2:
50
- u, a = h
 
 
 
51
  prompt += f"<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n"
52
 
53
  prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
 
54
  output = ""
55
  for token in llm(prompt, max_tokens=2048, temperature=0.2, top_p=0.9, repeat_penalty=1.1, stream=True):
56
- if stop_event.is_set():
57
- stop_event.clear()
58
- break
59
  output += token["choices"][0]["text"]
60
  yield output
61
 
62
- def copy_last(history):
63
- if history:
64
- last = history[-1]
65
- if isinstance(last, dict):
66
- return last["message"]
67
- return last[1]
68
- return ""
69
-
70
- def download_history(history):
71
- text = ""
72
- for h in history:
73
- if isinstance(h, dict):
74
- text += f'{h["role"]}: {h["message"]}\n\n'
75
- else:
76
- text += f'User: {h[0]}\nAI: {h[1]}\n\n'
77
- file_path = "chat_history.txt"
78
- with open(file_path, "w", encoding="utf-8") as f:
79
- f.write(text)
80
- return file_path # return path for gr.File output
81
-
82
- def edit_message(history, index, new_text):
83
- if index < len(history):
84
- if isinstance(history[index], dict):
85
- history[index]["message"] = new_text
86
- else:
87
- history[index] = (new_text, history[index][1])
88
- return history
89
-
90
  # ----------------------------
91
  # FastAPI API
92
  # ----------------------------
93
  app = FastAPI()
 
94
  class ChatRequest(BaseModel):
95
  message: str
96
  history: list = []
@@ -102,6 +79,7 @@ def chat_endpoint(request: ChatRequest):
102
  for u, a in request.history:
103
  prompt += f"<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n"
104
  prompt += f"<|im_start|>user\n{request.message}<|im_end|>\n<|im_start|>assistant\n"
 
105
  for token in llm(prompt, max_tokens=2048, temperature=0.2, top_p=0.9, repeat_penalty=1.1, stream=True):
106
  output += token["choices"][0]["text"]
107
  return {"response": output}
@@ -109,47 +87,30 @@ def chat_endpoint(request: ChatRequest):
109
  # ----------------------------
110
  # Gradio UI
111
  # ----------------------------
112
- with gr.Blocks() as demo:
113
- with gr.Column():
114
- chatbot = gr.Chatbot(height=700)
115
- state = gr.State([])
116
- msg = gr.Textbox(placeholder="Type your message...", container=False)
117
-
118
- with gr.Row():
119
- send_btn = gr.Button("Send")
120
- stop_btn = gr.Button("πŸ›‘ Stop")
121
- copy_btn = gr.Button("πŸ“‹ Copy Last")
122
- download_file = gr.File(label="Download Chat", file_types=[".txt"])
123
-
124
- with gr.Row():
125
- edit_index = gr.Number(label="Edit Index")
126
- edit_text = gr.Textbox(label="New Text")
127
- edit_btn = gr.Button("✏️ Edit")
128
-
129
- # ----------------------------
130
- # Callbacks
131
- # ----------------------------
132
- send_btn.click(generate_response, [msg, state], [chatbot, state])
133
- stop_btn.click(lambda: stop_event.set())
134
- copy_btn.click(copy_last, inputs=[state], outputs=None)
135
- download_file.output = download_history # assign output function
136
- edit_btn.click(edit_message, inputs=[state, edit_index, edit_text], outputs=[chatbot])
137
 
 
 
 
 
 
 
 
138
  demo.css = """
139
  .gradio-container {
140
- width: 100vw !important;
141
- height: 100vh !important;
142
- border-radius: 0px !important;
143
- overflow: hidden;
144
- background-color: #0b0f19 !important;
145
- }
146
- .input-textbox textarea {
147
  border-radius: 25px !important;
 
 
 
148
  }
149
- .message.user { border-radius: 18px 18px 4px 18px !important; background:#2b6fff !important; color:white !important;}
150
- .message.bot { border-radius: 18px 18px 18px 4px !important; background:#1c1f2a !important; color:white !important;}
151
  """
152
 
 
 
 
153
  def run_gradio():
154
  demo.launch(server_name="0.0.0.0", server_port=7860)
155
 
 
5
  from huggingface_hub import hf_hub_download
6
  from fastapi import FastAPI
7
  from pydantic import BaseModel
8
+ from threading import Thread
9
  import uvicorn
10
 
 
 
11
  # ----------------------------
12
  # Model
13
  # ----------------------------
 
27
 
28
  llm("warmup", max_tokens=1)
29
 
30
+ # ----------------------------
31
+ # System Prompt
32
+ # ----------------------------
33
  SYSTEM_PROMPT = """
34
  You are an advanced AI assistant.
35
  Answer questions clearly and concisely.
36
+ You can handle multi-turn conversations and provide detailed responses if needed.
37
  """
38
 
39
  # ----------------------------
40
+ # Chat Function
41
  # ----------------------------
42
  def generate_response(message, history):
43
  yield "πŸ€– Thinking..."
44
+ time.sleep(0.5)
45
+
46
  prompt = f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
47
  for h in history:
48
+ if isinstance(h, dict) and "role" in h and "message" in h:
49
  role = h["role"]
50
  msg = h["message"]
51
+ if role == "user":
52
+ prompt += f"<|im_start|>user\n{msg}<|im_end|>\n"
53
+ else:
54
+ prompt += f"<|im_start|>assistant\n{msg}<|im_end|>\n"
55
+ elif isinstance(h, (list, tuple)) and len(h) >= 2:
56
+ u, a = h[0], h[1]
57
  prompt += f"<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n"
58
 
59
  prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
60
+
61
  output = ""
62
  for token in llm(prompt, max_tokens=2048, temperature=0.2, top_p=0.9, repeat_penalty=1.1, stream=True):
 
 
 
63
  output += token["choices"][0]["text"]
64
  yield output
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  # ----------------------------
67
  # FastAPI API
68
  # ----------------------------
69
  app = FastAPI()
70
+
71
  class ChatRequest(BaseModel):
72
  message: str
73
  history: list = []
 
79
  for u, a in request.history:
80
  prompt += f"<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n"
81
  prompt += f"<|im_start|>user\n{request.message}<|im_end|>\n<|im_start|>assistant\n"
82
+
83
  for token in llm(prompt, max_tokens=2048, temperature=0.2, top_p=0.9, repeat_penalty=1.1, stream=True):
84
  output += token["choices"][0]["text"]
85
  return {"response": output}
 
87
  # ----------------------------
88
  # Gradio UI
89
  # ----------------------------
90
+ with gr.Blocks(theme=gr.Theme.from_hub("JackismyShephard/ultimate-rvc-theme")) as demo:
91
+ gr.HTML("<h2 style='text-align:center; color:white;'>Code Explainer AI</h2>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ chatbot = gr.ChatInterface(
94
+ fn=generate_response,
95
+ chatbot=gr.Chatbot(height=600),
96
+ textbox=gr.Textbox(placeholder="Paste code or ask for explanation...", container=False)
97
+ )
98
+
99
+ # Rounded corners for main container
100
  demo.css = """
101
  .gradio-container {
 
 
 
 
 
 
 
102
  border-radius: 25px !important;
103
+ max-width: 600px !important;
104
+ margin: auto !important;
105
+ overflow: hidden;
106
  }
107
+ .message.user { border-radius: 18px 18px 4px 18px !important; }
108
+ .message.bot { border-radius: 18px 18px 18px 4px !important; }
109
  """
110
 
111
+ # ----------------------------
112
+ # Run Gradio + FastAPI together
113
+ # ----------------------------
114
  def run_gradio():
115
  demo.launch(server_name="0.0.0.0", server_port=7860)
116