neovalle's picture
Update app.py
282332d verified
import gradio as gr
import csv
import re
import tempfile
import os
import requests
# Load system prompt from file
with open("system_instructions.txt", "r", encoding="utf-8") as f:
ECO_PROMPT = f.read()
# Hugging Face configuration
HF_API_KEY = os.environ.get("HF_API_KEY")
HF_API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"
def format_llama3_prompt(system_prompt, question, answer):
"""Format prompt according to Llama3's chat template"""
return f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
{system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|>
Question: {question}
Answer: {answer}
Please provide a numerical score between 1-5 based on the guidelines.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""
def score_qa(question, answer):
"""Get score from Llama3 via Hugging Face API"""
try:
prompt = format_llama3_prompt(ECO_PROMPT, question, answer)
headers = {
"Authorization": f"Bearer {HF_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"inputs": prompt,
"parameters": {
"max_new_tokens": 5,
"temperature": 0.1,
"return_full_text": False
}
}
response = requests.post(HF_API_URL, json=payload, headers=headers)
response.raise_for_status()
output = response.json()[0]['generated_text']
match = re.search(r"\d+", output)
return int(match.group(0)) if match else 1
except Exception as e:
print(f"API Error: {str(e)}")
return 1 # Fallback score
def judge_ecolinguistics_from_csv(csv_file):
"""Process CSV and generate results (unchanged from original)"""
rows = []
with open(csv_file.name, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = list(reader)
results = []
total_score = 0
for r in rows:
sc = score_qa(r.get("question", ""), r.get("answer", ""))
total_score += sc
results.append({
"question_number": r.get("question_number", ""),
"score": sc
})
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".csv", encoding="utf-8") as out_file:
writer = csv.DictWriter(out_file, fieldnames=["question_number", "score"])
writer.writeheader()
writer.writerows(results)
writer.writerow({"question_number": "Total", "score": total_score})
out_path = out_file.name
percentage = (total_score / (len(rows) * 5)) * 100 if rows else 0.0
percentage_display = f"""
<div style="
padding: 25px;
background: #f0fff4;
border-radius: 12px;
margin: 20px 0;
text-align: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
">
<h3 style="color: #22543d; margin: 0; font-size: 1.4em;">
🌱 Overall Score: <span style="color: #38a169;">{percentage:.1f}%</span>
</h3>
</div>
"""
return out_path, percentage_display
# Custom theme and styling (unchanged from original)
custom_theme = gr.themes.Default().set(
body_background_fill="#f8fff9",
button_primary_background_fill="#38a169",
button_primary_text_color="#ffffff",
button_primary_background_fill_hover="#2e7d32",
)
css = """
.gradio-container { max-width: 800px !important; }
#upload-box {
border: 2px dashed #38a169 !important;
padding: 30px !important;
border-radius: 15px !important;
background: #f8fff9 !important;
min-height: 150px !important;
}
#upload-box:hover {
border-color: #2e7d32 !important;
background: #f0fff4 !important;
}
#download-box {
border: 2px solid #38a169 !important;
padding: 20px !important;
border-radius: 15px !important;
background: #f8fff9 !important;
}
#logo {
border-radius: 15px !important;
border: 2px solid #38a169 !important;
padding: 5px !important;
background: white !important;
}
.dark #logo { background: #f0fff4 !important; }
.footer {
text-align: center;
padding: 15px !important;
background: #e8f5e9 !important;
border-radius: 8px !important;
margin-top: 25px !important;
}
"""
with gr.Blocks(theme=custom_theme, css=css) as demo:
# Header Section
with gr.Row():
gr.Image("logo.png",
show_label=False,
width=200,
height=200,
elem_id="logo")
gr.Markdown("""
<div style="margin-left: 25px;">
<h1 style="margin: 0; color: #22543d; font-size: 2.2em;">🌿 EcoLingua</h1>
<p style="margin: 10px 0 0 0; color: #38a169; font-size: 1.1em;">
Sustainable Communication Assessment Platform
</p>
</div>
""")
# Main Content
with gr.Column(variant="panel"):
gr.Markdown("""
## πŸ“€ Upload Your Q&A CSV
<div style="
background: #f0fff4;
padding: 20px;
border-radius: 10px;
margin: 15px 0;
">
<p style="margin: 0 0 10px 0; font-weight: 500;">Required CSV format:</p>
<div style="
background: white;
padding: 15px;
border-radius: 8px;
font-family: monospace;
">
question_number,question,answer<br>
1,"Question text...","Answer text..."<br>
2,"Another question...","Another answer..."
</div>
</div>
""")
with gr.Row():
csv_input = gr.File(
label=" ",
file_types=[".csv"],
elem_id="upload-box"
)
csv_output = gr.File(
label="Download Results",
interactive=False,
elem_id="download-box"
)
html_output = gr.HTML()
csv_input.change(
judge_ecolinguistics_from_csv,
inputs=csv_input,
outputs=[csv_output, html_output]
)
# Footer
gr.Markdown("""
<div class="footer">
<p style="margin: 0; color: #2e7d32; font-size: 0.9em;">
πŸƒ Powered by Meta Llama3 | Environmentally Conscious Language Analysis πŸƒ
</p>
</div>
""")
if __name__ == "__main__":
demo.launch()