Spaces:
Sleeping
Sleeping
File size: 5,315 Bytes
8425030 | 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | import gradio as gr
import pandas as pd
import requests
import json
from datetime import datetime
import os
# Groq API configuration
GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Set this in Hugging Face secrets
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
MODEL_NAME = "mixtral-8x7b-32768" # Free model from Groq
# CSS for attractive UI
css = """
.gradio-container {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.header {
text-align: center;
padding: 20px;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 8px;
margin-bottom: 20px;
}
.data-table {
background-color: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.submit-btn {
background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%) !important;
border: none !important;
color: white !important;
}
.submit-btn:hover {
transform: scale(1.02);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2) !important;
}
"""
# Initialize data storage
if not os.path.exists("data"):
os.makedirs("data")
def save_to_csv(data):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"data/entries_{timestamp}.csv"
df = pd.DataFrame([data])
df.to_csv(filename, mode='a', header=not os.path.exists(filename), index=False)
return filename
def query_groq(prompt):
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": MODEL_NAME,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7
}
response = requests.post(GROQ_API_URL, headers=headers, data=json.dumps(payload))
return response.json()["choices"][0]["message"]["content"]
def process_form(name, email, age, country, feedback, subscribe):
# Validate inputs
if not all([name, email, age]):
return "❗ Please fill in all required fields", None
data = {
"Name": name,
"Email": email,
"Age": age,
"Country": country,
"Feedback": feedback,
"Subscribed": "Yes" if subscribe else "No",
"Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
# Save data
filename = save_to_csv(data)
# Generate AI response
ai_prompt = f"User {name} from {country} submitted feedback: '{feedback}'. Generate a friendly thank you message."
ai_response = query_groq(ai_prompt)
# Display results
df = pd.DataFrame([data])
return ai_response, df
def show_data():
if not os.path.exists("data"):
return pd.DataFrame(columns=["Name", "Email", "Age", "Country", "Feedback", "Subscribed", "Timestamp"])
all_files = [f for f in os.listdir("data") if f.endswith('.csv')]
if not all_files:
return pd.DataFrame(columns=["Name", "Email", "Age", "Country", "Feedback", "Subscribed", "Timestamp"])
dfs = [pd.read_csv(f"data/{f}") for f in all_files]
return pd.concat(dfs, ignore_index=True)
with gr.Blocks(css=css) as demo:
with gr.Column():
gr.Markdown("""
<div class="header">
<h1>🌟 Data Collection Pro</h1>
<p>Share your feedback with us and get an AI-generated response!</p>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
name = gr.Textbox(label="Full Name*", placeholder="Enter your name")
email = gr.Textbox(label="Email*", placeholder="your@email.com")
age = gr.Number(label="Age*", minimum=1, maximum=120)
country = gr.Dropdown(
label="Country",
choices=["USA", "UK", "Canada", "Australia", "India", "Other"],
value="USA"
)
subscribe = gr.Checkbox(label="Subscribe to newsletter", value=True)
with gr.Column(scale=2):
feedback = gr.Textbox(
label="Your Feedback",
lines=5,
placeholder="Share your thoughts with us...",
max_lines=10
)
submit_btn = gr.Button("Submit Form", elem_classes="submit-btn")
with gr.Row():
ai_output = gr.Textbox(label="AI Response", interactive=False)
data_output = gr.Dataframe(
label="Your Submission",
headers=["Name", "Email", "Age", "Country", "Feedback", "Subscribed", "Timestamp"],
elem_classes="data-table"
)
with gr.Accordion("View All Entries", open=False):
all_data = gr.Dataframe(
label="All Submissions",
headers=["Name", "Email", "Age", "Country", "Feedback", "Subscribed", "Timestamp"],
elem_classes="data-table",
interactive=False
)
refresh_btn = gr.Button("Refresh Data")
submit_btn.click(
fn=process_form,
inputs=[name, email, age, country, feedback, subscribe],
outputs=[ai_output, data_output]
)
refresh_btn.click(fn=show_data, outputs=all_data)
demo.launch() |