Spaces:
No application file
No application file
File size: 2,217 Bytes
d094e72 |
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 |
import gradio as gr
from transformers import pipeline
import uuid
# β
Using a public model to avoid authentication issues
generator = pipeline("text-generation", model="tiiuae/falcon-7b-instruct")
user_sessions = {}
def get_session(session_id):
if session_id not in user_sessions:
user_sessions[session_id] = {"chat": []}
return user_sessions[session_id]
def build_prompt(history):
prompt = "You are a helpful assistant.\n"
for turn in history:
prompt += f"User: {turn[0]}\nAssistant: {turn[1]}\n"
return prompt
def chat_fn(user_input, session_id):
session = get_session(session_id)
history = session["chat"]
prompt = build_prompt(history + [[user_input, ""]]) + "Assistant:"
result = generator(prompt, max_new_tokens=128, do_sample=True, temperature=0.7)[0]["generated_text"]
reply = result[len(prompt):].strip().split("\n")[0]
history.append([user_input, reply])
return history, session_id
def upload_handler(file):
try:
content = file.read().decode("utf-8")
return content
except Exception as e:
return f"Error: {str(e)}"
def code_viewer(code):
return "Code received. Execution is disabled on this free demo for safety."
def create_session():
return str(uuid.uuid4())
with gr.Blocks(title="Multi-Tool AI Chatbot") as demo:
session_id_state = gr.State(value=create_session())
with gr.Tab("π€ Chatbot"):
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Your message")
send = gr.Button("Send")
send.click(fn=lambda msg, sid: chat_fn(msg, sid), inputs=[msg, session_id_state], outputs=[chatbot, session_id_state])
with gr.Tab("π File Reader"):
file_input = gr.File(label="Upload .txt file", file_types=[".txt"])
file_output = gr.Textbox(label="File content")
file_input.change(upload_handler, inputs=file_input, outputs=file_output)
with gr.Tab("π» Code Viewer"):
code_input = gr.Code(language="python", label="Enter Python code")
code_output = gr.Textbox(label="Output")
run_btn = gr.Button("View Output")
run_btn.click(fn=code_viewer, inputs=code_input, outputs=code_output)
demo.launch() |