import gradio as gr import pandas as pd import os import datetime import requests from huggingface_hub import HfApi from groq import Groq # ====== CONFIG ====== HF_TOKEN = os.getenv("HF_TOKEN") REPO_ID = "abhidgp1978/user_tickets" FILENAME = "user_tickets.csv" LOCAL_CSV = "user_tickets.csv" JIRA_URL = os.getenv("JIRA_URL") # e.g. https://your-domain.atlassian.net JIRA_EMAIL = os.getenv("JIRA_EMAIL") JIRA_API_TOKEN = os.getenv("JIRA_API_TOKEN") client = Groq(api_key=os.getenv("GROQ_API_KEY")) hf_api = HfApi() # ====== LOAD DATASET LOCALLY ====== if not os.path.exists(LOCAL_CSV): try: hf_api.hf_hub_download( repo_id=REPO_ID, filename=FILENAME, repo_type="dataset", local_dir="." ) except Exception: pd.DataFrame(columns=["Name", "Email", "Project", "Task Brief", "Output", "Timestamp", "Jira Issue Key"]).to_csv(LOCAL_CSV, index=False) # ====== JIRA API HELPERS ====== jira_auth = (JIRA_EMAIL, JIRA_API_TOKEN) jira_headers = { "Accept": "application/json", "Content-Type": "application/json" } # Helper function to convert seconds to a readable time format (e.g., 5h 30m) def format_time(seconds): if seconds is None: return "0h 0m" hours = seconds // 3600 minutes = (seconds % 3600) // 60 return f"{hours}h {minutes}m" def get_jira_projects(): url = f"{JIRA_URL}/rest/api/3/project/search" response = requests.get(url, auth=jira_auth, headers=jira_headers) if response.status_code != 200: print(f"❌ Project fetch failed. Status: {response.status_code}. Response: {response.text}") return [] projects = response.json().get("values", []) return [f"{p['key']} - {p['name']}" for p in projects] def create_jira_issue(project_key, summary, description_text): url = f"{JIRA_URL}/rest/api/3/issue" description_adf = { "type": "doc", "version": 1, "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": description_text } ] } ] } payload = { "fields": { "project": {"key": project_key}, "summary": summary[:255], "description": description_adf, "issuetype": {"name": "Task"} } } response = requests.post(url, auth=jira_auth, headers=jira_headers, json=payload) if response.status_code == 201: return response.json().get("key") else: print(f"❌ Jira issue creation failed! Status code: {response.status_code}") print("Response content:", response.text) return None def fetch_project_issues_for_report(project_key): # Requesting both potential Epic linkage fields for full compatibility fields = "issuetype,summary,status,timetracking,parent,customfield_10001" jql = f'project="{project_key}" ORDER BY issuetype DESC, created ASC' # Corrected: Using the non-deprecated /rest/api/3/search/jql endpoint url = f"{JIRA_URL}/rest/api/3/search/jql" params = {"jql": jql, "maxResults": 1000, "fields": fields} response = requests.get(url, auth=jira_auth, headers={"Accept": "application/json"}, params=params) if response.status_code != 200: print(f"❌ DEBUG: Failed to fetch issues for report. Status code: {response.status_code}. Response: {response.text}") return [] issues = response.json().get("issues", []) print(f"✅ DEBUG: Successfully fetched {len(issues)} issues for project {project_key}.") return issues def generate_project_report(project_key_selection): print("--- DEBUG: Starting generate_project_report ---") if not project_key_selection: return (gr.update(value="Please select a project."), gr.update(visible=False), gr.update(visible=False)) project_key = project_key_selection.split(" - ")[0] issues = fetch_project_issues_for_report(project_key) epics_map = {} epic_tasks_count = {} total_original_estimate_seconds = 0 total_time_spent_seconds = 0 for issue in issues: fields = issue['fields'] issue_type = fields['issuetype']['name'] time_tracking = fields.get('timetracking', {}) # Aggregate time if time_tracking.get('originalEstimateSeconds'): total_original_estimate_seconds += time_tracking['originalEstimateSeconds'] if time_tracking.get('timeSpentSeconds'): total_time_spent_seconds += time_tracking['timeSpentSeconds'] # 1. Epic identification if issue_type.lower() == 'epic': key = issue['key'] epics_map[key] = { "Key": key, "Summary": fields['summary'], "Status": fields['status']['name'], "Child_Issues": 0 } epic_tasks_count[key] = 0 # 2. Task/Story linkage (FIXED: Robust dual-check for Epic link field) else: epic_key = None # --- Check 1: Next-Gen/Sub-Task 'parent' field structure --- # Use .get('key') inside the parent object, as seen in the debug output parent_link = fields.get('parent', {}) epic_key = parent_link.get('key') # --- Check 2: Classic Epic Link 'customfield_10001' field (Fallback) --- if not epic_key: classic_epic_link = fields.get('customfield_10001') if classic_epic_link: # customfield_10001 holds the Epic Key string directly epic_key = classic_epic_link # Update count if a valid Epic key was found and it exists in our epics map if epic_key and epic_key in epic_tasks_count: epic_tasks_count[epic_key] += 1 print(f"--- DEBUG: Total Epics found: {len(epics_map)} ---") print(f"--- DEBUG: Epic Task Counts: {epic_tasks_count} ---") # --- Final Report Generation --- # Combine Epic details with child issue counts final_epics_data = [] for key, details in epics_map.items(): details["Child_Issues"] = epic_tasks_count.get(key, 0) final_epics_data.append(details) total_estimated_time = format_time(total_original_estimate_seconds) total_logged_time = format_time(total_time_spent_seconds) # 1. Project Health Status (Simple Placeholder) health_status = "Green 🟢" if total_original_estimate_seconds > 0: if total_time_spent_seconds > total_original_estimate_seconds * 1.2: health_status = "Red 🔴" elif total_time_spent_seconds > total_original_estimate_seconds: health_status = "Yellow 🟡" health_report = f""" ### Project: {project_key_selection} | Metric | Value | | :--- | :--- | | **Health Status** | **{health_status}** | | **Total Epics** | **{len(final_epics_data)}** | *Note: Health is currently determined by comparing Total Logged Time to Total Estimated Time.* """ # 2. Epic Details Report epic_data = [ [ epic["Key"], epic["Summary"], f'{epic["Status"]} ({epic["Child_Issues"]} Tasks/Stories)' # Display task count ] for epic in final_epics_data ] epic_df_headers = ["Epic Key", "Epic Summary", "Epic Status & Task Count"] # 3. Time Report (Split based on estimated time) dev_time_est = format_time(total_original_estimate_seconds * 0.4) qa_time_est = format_time(total_original_estimate_seconds * 0.3) design_time_est = format_time(total_original_estimate_seconds * 0.15) pm_time_est = format_time(total_original_estimate_seconds * 0.15) time_report_markdown = f""" ### Time Breakdown for {project_key} | Time Category | Estimated Time | Logged Time (Total) | | :--- | :--- | :--- | | **Total Project Time** | **{total_estimated_time}** | **{total_logged_time}** | | Dev Time (Est. 40%) | {dev_time_est} | *Requires custom Jira field/label aggregation* | | QA Time (Est. 30%) | {qa_time_est} | *Requires custom Jira field/label aggregation* | | Design Time (Est. 15%) | {design_time_est} | *Requires custom Jira field/label aggregation* | | Project Mgmt Time (Est. 15%) | {pm_time_est} | *Requires custom Jira field/label aggregation* | """ return ( gr.update(value=health_report, visible=True), gr.update(headers=epic_df_headers, value=epic_data, visible=True), gr.update(value=time_report_markdown, visible=True) ) # ====== AI GENERATION FUNCTION (Updated to remove Test Cases rule) ====== def generate_ticket(name, email, task_brief): # Rule 3 (**Test Cases**) has been removed from the prompt as requested. prompt = f""" You are a task documentation assistant. Based on the given task brief, create a Markdown-formatted output with these rules: 1. **Description** — Less than 500 words but do NOT cut sentences abruptly. Should be clear enough for Developer, QA, and Designer. 2. **Acceptance Criteria** — Bullet points. 3. All section headings must be in **bold**. 4. Keep everything in one Markdown block (no extra boxes). Task Brief: {task_brief} """ try: response = client.chat.completions.create( model="openai/gpt-oss-20b", messages=[{"role": "user", "content": prompt}], temperature=0.5, max_tokens=1000 ) output_text = response.choices[0].message.content.strip() except Exception as e: output_text = f"⚠️ AI generation failed: {e}" return output_text return output_text # ====== GRADIO UI ====== with gr.Blocks() as demo: # --- Tab 1: Submission Agent --- with gr.Tab("Submission Agent") as submission_tab: gr.Markdown("## Jira Task Description Agent") gr.Markdown("Fill in your details, select a Jira project, add your task brief, generate detailed task description, edit if needed, then submit to Jira.") with gr.Row(): name = gr.Textbox(label="Your Name", placeholder="Enter full name") email = gr.Textbox(label="Your Email", placeholder="Enter email address") jira_projects = gr.Dropdown( label="Select Jira Project", choices=[], allow_custom_value=False, multiselect=False, value=None ) task_brief = gr.Textbox(label="Task Brief", placeholder="Enter short description of the task", lines=3) generate_btn = gr.Button("Generate Details") output = gr.Textbox(label="Generated Details (Editable Markdown)", lines=20) submit_btn = gr.Button("Submit Ticket") submission_status = gr.Textbox(label="Submission Status", interactive=False) # --- Tab 2: Projects details report --- with gr.Tab("Projects details report") as report_tab: gr.Markdown("## Project Report") gr.Markdown("Select a project to generate a summary of Epics and an estimated time breakdown.") report_project_dropdown = gr.Dropdown( label="Select Project for Report", choices=[], # Will be populated by load_projects allow_custom_value=False, multiselect=False, value=None ) generate_report_btn = gr.Button("Generate Project Report") # Output components for the report report_health = gr.Markdown(label="Project Health & Stats", visible=False) gr.Markdown("### Epic Details Report") report_epic_df = gr.Dataframe( headers=["Epic Key", "Epic Summary", "Epic Status & Task Count"], datatype=["str", "str", "str"], interactive=False, visible=False ) gr.Markdown("### Time Breakdown Report") report_time = gr.Markdown(label="Time Report", visible=False) # ====== FUNCTIONS FOR GRADIO INTERACTION ====== def load_projects(): projects = get_jira_projects() if projects: # Update both dropdowns on load return ( gr.update(choices=projects, value=projects[0]), # Submission tab dropdown gr.update(choices=projects, value=projects[0]) # Report tab dropdown ) else: return ( gr.update(choices=[], value=None), gr.update(choices=[], value=None) ) def generate_details(name, email, task_brief): if not (name and email and task_brief): return "⚠️ Please fill Name, Email, and Task Brief." details = generate_ticket(name, email, task_brief) return details def submit_ticket(name, email, project_selection, task_brief, edited_details): if not (name and email and project_selection and task_brief and edited_details): return "⚠️ Please fill all fields and generate details before submitting." project_key = project_selection.split(" - ")[0] summary = f"{task_brief.strip()} - Jira ticket created by {name.strip()}" if len(summary) > 255: summary = summary[:252] + "..." issue_key = create_jira_issue(project_key, summary, edited_details) if not issue_key: return "⚠️ Failed to create Jira issue." timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") new_entry = pd.DataFrame([{ "Name": name, "Email": email, "Project": project_selection, "Task Brief": task_brief, "Output": edited_details, "Timestamp": timestamp, "Jira Issue Key": issue_key }]) if os.path.exists(LOCAL_CSV): df = pd.read_csv(LOCAL_CSV) df = pd.concat([df, new_entry], ignore_index=True) else: df = new_entry df.to_csv(LOCAL_CSV, index=False) try: hf_api.upload_file( path_or_fileobj=LOCAL_CSV, path_in_repo=FILENAME, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN ) except Exception as e: print("⚠️ Error uploading to HF dataset:", e) return f"✅ Jira ticket created: {issue_key}" # ====== EVENT HANDLERS ====== # Submission Agent Handlers (Unchanged) generate_btn.click( fn=generate_details, inputs=[name, email, task_brief], outputs=output ) submit_btn.click( fn=submit_ticket, inputs=[name, email, jira_projects, task_brief, output], outputs=[submission_status] ) # Project Report Handler (FIXED) generate_report_btn.click( fn=generate_project_report, inputs=[report_project_dropdown], outputs=[report_health, report_epic_df, report_time] ) # Load projects on demo start demo.load( fn=load_projects, outputs=[jira_projects, report_project_dropdown] ) demo.launch()