Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pollinations as pl
|
3 |
+
import pandas as pd
|
4 |
+
import os
|
5 |
+
from datetime import datetime
|
6 |
+
from huggingface_hub import HfApi
|
7 |
+
import pyarrow.parquet as pq
|
8 |
+
import pyarrow as pa
|
9 |
+
import requests
|
10 |
+
import json
|
11 |
+
|
12 |
+
# Initialize Pollinations text model (default)
|
13 |
+
default_model = "openai"
|
14 |
+
model = pl.Text(model=default_model, contextual=True)
|
15 |
+
|
16 |
+
# Hugging Face setup
|
17 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # Set in HF Space secrets
|
18 |
+
REPO_ID = "kulia-moon/conza"
|
19 |
+
api = HfApi()
|
20 |
+
|
21 |
+
# Store conversation history
|
22 |
+
conversation_history = []
|
23 |
+
|
24 |
+
# Fetch available models
|
25 |
+
def fetch_models():
|
26 |
+
try:
|
27 |
+
response = requests.get("https://text.pollinations.ai/models")
|
28 |
+
response.raise_for_status()
|
29 |
+
models = response.json()
|
30 |
+
return models, gr.update(choices=[m["id"] for m in models], value=default_model)
|
31 |
+
except Exception as e:
|
32 |
+
return {"error": f"Failed to fetch models: {e}"}, gr.update(choices=[default_model], value=default_model)
|
33 |
+
|
34 |
+
def change_model(selected_model):
|
35 |
+
global model
|
36 |
+
model = pl.Text(model=selected_model, contextual=True)
|
37 |
+
return f"Switched to model: {selected_model}"
|
38 |
+
|
39 |
+
def chatbot_response(user_message, history, selected_model):
|
40 |
+
global conversation_history, model
|
41 |
+
# Ensure model is up-to-date
|
42 |
+
if model.model != selected_model:
|
43 |
+
model = pl.Text(model=selected_model, contextual=True)
|
44 |
+
|
45 |
+
# Generate response
|
46 |
+
seed = int(datetime.now().timestamp()) # Use timestamp as seed
|
47 |
+
response = model(user_message, seed=seed)
|
48 |
+
|
49 |
+
# Append to history with timestamp and model info
|
50 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
51 |
+
conversation_history.append({
|
52 |
+
"timestamp": timestamp,
|
53 |
+
"user_message": user_message,
|
54 |
+
"bot_response": response,
|
55 |
+
"model": selected_model
|
56 |
+
})
|
57 |
+
|
58 |
+
# Update Gradio history
|
59 |
+
history.append((user_message, response))
|
60 |
+
|
61 |
+
# Save to Parquet and push to HF
|
62 |
+
save_conversation()
|
63 |
+
|
64 |
+
return history
|
65 |
+
|
66 |
+
def save_conversation():
|
67 |
+
if not conversation_history:
|
68 |
+
return
|
69 |
+
# Convert to DataFrame
|
70 |
+
df = pd.DataFrame(conversation_history)
|
71 |
+
# Generate filename with timestamp
|
72 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
73 |
+
filename = f"conversation_{timestamp}.parquet"
|
74 |
+
# Save to Parquet
|
75 |
+
table = pa.Table.from_pandas(df)
|
76 |
+
pq.write_table(table, filename)
|
77 |
+
# Push to Hugging Face
|
78 |
+
try:
|
79 |
+
api.upload_file(
|
80 |
+
path_or_fileobj=filename,
|
81 |
+
path_in_repo=f"data/{filename}",
|
82 |
+
repo_id=REPO_ID,
|
83 |
+
repo_type="dataset",
|
84 |
+
token=HF_TOKEN
|
85 |
+
)
|
86 |
+
os.remove(filename) # Clean up local file
|
87 |
+
except Exception as e:
|
88 |
+
print(f"Error uploading to Hugging Face: {e}")
|
89 |
+
|
90 |
+
# Create Gradio interface
|
91 |
+
with gr.Blocks() as demo:
|
92 |
+
gr.Markdown("# Pollinations AI Chatbot")
|
93 |
+
with gr.Row():
|
94 |
+
with gr.Column(scale=3):
|
95 |
+
chatbot = gr.Chatbot()
|
96 |
+
msg = gr.Textbox(placeholder="Type your message...")
|
97 |
+
model_selector = gr.Dropdown(label="Select Model", choices=[default_model])
|
98 |
+
change_model_btn = gr.Button("Change Model")
|
99 |
+
clear = gr.Button("Clear")
|
100 |
+
with gr.Column(scale=1):
|
101 |
+
models_output = gr.JSON(label="Pollinations Models")
|
102 |
+
|
103 |
+
# Fetch models on load
|
104 |
+
models_output, model_selector = fetch_models()
|
105 |
+
|
106 |
+
def user_input(user_message, history):
|
107 |
+
return "", history + [[user_message, None]]
|
108 |
+
|
109 |
+
def bot_response(history, selected_model):
|
110 |
+
if not history or not history[-1][0]:
|
111 |
+
return history
|
112 |
+
user_message = history[-1][0]
|
113 |
+
history = chatbot_response(user_message, history, selected_model)
|
114 |
+
return history
|
115 |
+
|
116 |
+
# Event handlers
|
117 |
+
msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
118 |
+
bot_response, [chatbot, model_selector], chatbot
|
119 |
+
)
|
120 |
+
change_model_btn.click(change_model, model_selector, gr.State())
|
121 |
+
clear.click(lambda: ([], []), None, [chatbot, msg], queue=False)
|
122 |
+
|
123 |
+
# Launch the demo
|
124 |
+
demo.launch()
|