Spaces:
Sleeping

Data_entry / app.py
Ai1996's picture
Create app.py
8425030 verified
Raw History Blame Contribute Delete
5.32 kB
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()