""" Acknowledgement: The Smart Context Citation (SCC) system was developed by Dr. Majed Abuseif. The text fragments scroll functionality in the HTML environment is based on Burris and Bokan (2023). Conceptualisation, primary coding, integration, project management, and finalisation were undertaken by Dr. Majed Abuseif. Project planning, execution plan, and review were conducted by Dr. Majed Abuseif in collaboration with ChatGPT. Formatting and design were contributed by Dr. Majed Abuseif and Manus. Programming contributions were provided by Dr. Majed Abuseif and Grok, with hosting on Hugging Face. The code is implemented in Python. """ import streamlit as st import hashlib import urllib.parse from datetime import datetime import pytz import re import pandas as pd import base64 import io import openpyxl from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl.worksheet.hyperlink import Hyperlink # --- Constants --- MELBOURNE_TIMEZONE = 'Australia/Melbourne' # --- Custom CSS for simplified UI --- def load_css(): st.markdown(""" """, unsafe_allow_html=True) # --- Helper Functions --- def select_longest_segment(text): # Split text by various dashes (hyphen, non-breaking hyphen, en dash, em dash) dash_variants = ['\u002D', '\u2011', '\u2013', '\u2014'] segments = [text] for dash in dash_variants: new_segments = [] for segment in segments: new_segments.extend(segment.split(dash)) segments = new_segments # Return the longest segment, or original text if no dashes return max(segments, key=len, default=text).strip() def encode_text_fragment(text): # Encode text for W3C Text Fragments, preserving only regular hyphens (U+002D) # Non-breaking hyphens (U+2011) are encoded as %E2%80%91 # En dashes (U+2013) are encoded as %E2%80%93 # Em dashes (U+2014) are encoded as %E2%80%94 return urllib.parse.quote(text, safe='-') def generate_citation_hash(author, year, url, fragment_text, cited_text, username, task_name, current_date, current_time): # Normalize inputs by stripping whitespace fragment_text = select_longest_segment(fragment_text.strip()) cited_text = select_longest_segment(cited_text.strip()) task_name = task_name.strip() author = author.strip() url = url.strip() username = username.strip() data = f"{author}, {year} | {url} | {fragment_text} | {cited_text} | {username} | {task_name} | {current_date} | {current_time}" return hashlib.sha256(data.encode('utf-8')).hexdigest() def format_citation_html(url, fragment_text, author, year, scc_hash): # Select the longest segment for the text fragment to avoid breaking the link selected_fragment = select_longest_segment(fragment_text) encoded_fragment = encode_text_fragment(selected_fragment) full_url = f"{url}#:~:text={encoded_fragment}" return f'{author} ({year})' def format_metadata_html(url, author, year, scc_hash, username, task_name, current_date, current_time): # Use original task_name with em dashes for text fragment URL metadata = f"{username}—{task_name}—{current_date}—{current_time}" encoded_metadata = encode_text_fragment(metadata) full_url = f"{url}#:~:text={encoded_metadata}" return f'{author} ({year}). {scc_hash}' def check_for_fragment(url): return '#:~:text=' in url def parse_citation_text(citation_text): match = re.match(r'^(?:(\w[\w\s.,&et al]+)\s*\((\d{4})\)|\((\w[\w\s.,&et al]+),\s*(\d{4})\))$', citation_text.strip()) if match: author = match.group(1) or match.group(3) year = match.group(2) or match.group(4) author = author.strip() return author, year return None, None def parse_url(url): if not url: return None, None try: match = re.search(r'#:~:text=([^&]+)', url) fragment_text = urllib.parse.unquote(match.group(1)) if match else None base_url = url.split('#')[0] return base_url, fragment_text except: return None, None def parse_hash_text(hash_text): match = re.match(r'.*?\(\d{4}\)\.\s*([0-9a-f]{64})', hash_text.strip()) if match: return match.group(1) return None def parse_metadata(fragment_text): if not fragment_text: return None, None, None, None try: metadata_parts = fragment_text.split('—') if len(metadata_parts) == 4: username, task_name, date, time = metadata_parts return username, task_name, date, time return None, None, None, None except: return None, None, None, None def get_table_download_link(df, filename="citation_data.csv"): csv = df.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() href = f'Download Citation Data as CSV' return href def get_excel_download_link(df, filename="citation_data.xlsx"): output = io.BytesIO() wb = openpyxl.Workbook() ws = wb.active # Write headers headers = df.columns.tolist() ws.append(headers) # Write data rows for index, row in df.iterrows(): row_data = [] cell_positions = {} # track cell positions for hyperlink assignment urls = {} # store URLs per column for col_idx, col in enumerate(headers): value = row[col] if col in ["Citation", "SCC Index"]: # Extract URL and display text from HTML anchor tag match = re.search(r']*>([^<]+)', str(value)) if match: link_url, display_text = match.groups() row_data.append(display_text) # Position where this cell will be written (next row after append) cell_positions[col] = (ws.max_row + 1, col_idx + 1) urls[col] = link_url else: row_data.append(value) else: row_data.append(value) ws.append(row_data) # Apply hyperlinks after appending row for col, (r, c) in cell_positions.items(): cell = ws.cell(row=r, column=c) cell.hyperlink = urls[col] cell.hyperlink.tooltip = "Click to visit source" cell.style = "Hyperlink" wb.save(output) b64 = base64.b64encode(output.getvalue()).decode() href = f'Download citation data as Excel' return href # --- Live Clock JavaScript --- def live_clock(): return """
""" # --- Streamlit App --- st.set_page_config(layout="wide", page_title="Smart Context Citation Tool") # Load custom CSS load_css() # Main header st.markdown("""

Smart Context Citation (SCC) Tool

""", unsafe_allow_html=True) # Expandable section for About SCC and Example Citation with st.expander("About SCC and Example Citation"): st.markdown("""

The Smart Context Citation (SCC) style is a modern referencing system designed to enhance transparency and integrity in academic citations, particularly in the era of generative AI. It integrates context directly into citations, uses cryptographic hashes for verification, and replaces the traditional reference list with an SCC Index that includes an Authenticated Citation Identifier (ACI).

Key Features

Technical Legitimacy

The SCC style uses the W3C Text Fragments specification by Burris and Bokan (2023) to enable precise linking to specific sections of digital content. This ensures that citations are contextually accurate, verifiable, and aligned with modern digital standards.

Acknowledgement

Smart Context Citation (SCC) developed by Dr. Majed Abuseif, with contributions from ChatGPT, Manus-AI, and Grok, hosted on Hugging Face.

Example Citation

Inputs:

Outputs:

""", unsafe_allow_html=True) # Expandable section for SCC Style Guidelines with st.expander("SCC Style Guidelines"): st.markdown("""

The Smart Context Citation (SCC) style ensures accurate, transparent, and verifiable citations. Follow these steps to generate and verify citations using the SCC Tool.

Generating Citations

  1. Access the Tool: Open the "Citation Generator" tab.
  2. Enter User Information:
    • Username: Your unique identifier (e.g., Majed).
    • Task Name: The project or assignment name (e.g., Design Strategies for Trees on Buildings).
  3. Enter Citation Information:
    • Author(s) Name: The author(s) of the source (e.g., Abuseif et al.).
    • Publication Year: The year of publication (e.g., 2023).
    • Source URL: The full URL of the source, without text fragments (e.g., https://www.sciencedirect.com/science/article/pii/S2772411523000046).
    • Annotated Text: The sentence or paragraph containing the information you are referencing from the source (e.g., A proposed design framework for green roof settings in general and trees on buildings in particular).
  4. Generate Citation: Click the "Generate Citation" button.
  5. Copy Outputs:
    • Citation (Start of Text): Use "Author (Year)" for the start of a sentence (e.g., Abuseif et al. (2023)).
    • Citation (End of Text): Use "(Author, Year)" for in-text citations (e.g., (Abuseif et al., 2023)).
    • SCC Index: Copy the index link (e.g., Abuseif et al. (2023). cda7ba19e51e430107e58696758fdf79b8f016d8f27e8f8691ad713e7c8bc668) for verification.
    • If you would like to test the reference before using it, click on it to check whether it is suitable and captures the information you need.

Using References and the SCC Index in Your Document

  1. Paste the reference directly in the appropriate place within your document.
  2. Create an SCC Index (instead of a traditional reference list), and paste the corresponding SCC Index entry for each reference you’ve used.

Verifying Citations (for Markers and Reviewers)

  1. Access the Tool: Open the "Verify Citation" tab.
  2. Enter Citation Information:
    • Citation Text: Paste the citation text (e.g., Abuseif et al. (2023) or (Abuseif et al., 2023)).
    • Citation URL: Paste the hyperlink URL from the citation (right-click and select "Copy Link Address").
  3. Enter SCC Index Information:
    • SCC Index Text: Paste the index text (e.g., Abuseif et al. (2023). cda7ba19e51e430107e58696758fdf79b8f016d8f27e8f8691ad713e7c8bc668).
    • SCC Index URL: Paste the hyperlink URL from the index (right-click and select "Copy Link Address").
  4. Verify Citation: Click the "Verify Citation" button.
  5. Review Result:
    • Authentic Citation: Displayed in green if the hash matches, confirming integrity.
    • Unauthentic Citation: Displayed in red if the hash does not match, indicating potential tampering.
""", unsafe_allow_html=True) tabs = st.tabs(["Citation Generator", "Verify Citation"]) with tabs[0]: st.markdown('
', unsafe_allow_html=True) # User Information Section st.subheader("User Information") col1, col2 = st.columns(2) with col1: username = st.text_input("Username", help="Your username for tracking purposes", placeholder="e.g., Majed") with col2: task_name = st.text_input("Task Name", help="The name of the task or project", placeholder="e.g., Design Strategies for Trees on Buildings") # Citation Info Section st.subheader("Citation Info") col3, col4 = st.columns(2) with col3: author_name = st.text_input("Author(s) Name", help="The author(s) of the source", placeholder="e.g., Abuseif et al.") with col4: publication_year = st.text_input("Publication Year", help="The year of publication", placeholder="e.g., 2023") col5, col6 = st.columns(2) with col5: source_url = st.text_input("Source URL", help="The full URL of the source", placeholder="https://www.sciencedirect.com/science/article/pii/S2772411523000046") with col6: annotated_text = st.text_input("Annotated Text", help="The sentence or paragraph containing the information you are referencing from the source", placeholder="e.g., A proposed design framework for green roof settings...") # Live date and time display st.markdown("### Current Date and Time (AEST)") st.components.v1.html(live_clock(), height=50) # Get current date and time in Melbourne timezone for hash generation melbourne_tz = pytz.timezone(MELBOURNE_TIMEZONE) current_datetime_melbourne = datetime.now(melbourne_tz) current_date = current_datetime_melbourne.strftime("%Y-%m-%d") current_time = current_datetime_melbourne.strftime("%H:%M:%S") generate_button = st.button("Generate Citation", type="primary", use_container_width=True) if generate_button: if not all([username, task_name, author_name, publication_year, source_url, annotated_text]): st.error("Please fill in all fields before generating a citation.") elif check_for_fragment(source_url): st.markdown("""
Warning: Your URL already contains a text fragment, which suggests you may have used AI assistance in your research. Please revisit the source, review the context carefully, and copy the source link again—ensuring it does not include any existing fragments.
""", unsafe_allow_html=True) else: # Generate hash using normalized inputs scc_hash = generate_citation_hash(author_name, publication_year, source_url, annotated_text, annotated_text, username, task_name, current_date, current_time) citation_link_start = format_citation_html(source_url, annotated_text, author_name, publication_year, scc_hash) # Use the longest segment for the end-of-text citation link selected_fragment = select_longest_segment(annotated_text) citation_link_end = f'({author_name}, {publication_year})' metadata_link = format_metadata_html(source_url, author_name, publication_year, scc_hash, username, task_name, current_date, current_time) # --- Persistent Table with Clickable SCC Hash --- # First, ensure session state is initialized for the citation DataFrame if 'citation_df' not in st.session_state: st.session_state.citation_df = pd.DataFrame(columns=[ "Username", "Task Name", "Time", "Date", "Citation", "SCC Index", "Annotated Text" ]) # Create clickable HTML for SCC Index (full metadata link) clickable_index = metadata_link # Create new row data new_row = { "Username": username, "Task Name": task_name, "Time": current_time, "Date": current_date, "Citation": citation_link_start, "SCC Index": clickable_index, "Annotated Text": annotated_text } # Append the new row to the session state DataFrame new_df = pd.DataFrame([new_row]) st.session_state.citation_df = pd.concat([st.session_state.citation_df, new_df], ignore_index=True) # Get the accumulated DataFrame for display and download df = st.session_state.citation_df col_html1, col_html2 = st.columns(2) # HTML Citation - Start of Text with col_html1: st.markdown("### Citation (Start of Text)") st.markdown('
', unsafe_allow_html=True) st.markdown(citation_link_start, unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # HTML Citation - End of Text with col_html2: st.markdown("### Citation (End of Text)") st.markdown('
', unsafe_allow_html=True) st.markdown(citation_link_end, unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # SCC Index st.markdown("### SCC Index") st.markdown(metadata_link, unsafe_allow_html=True) # Display table after SCC Index st.markdown("### Citation Table") st.markdown(get_excel_download_link(df), unsafe_allow_html=True) st.markdown(df.to_html(classes="citation-table", index=False, escape=False), unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) with tabs[1]: st.markdown('
', unsafe_allow_html=True) st.subheader("Citation Information") citation_text = st.text_input("Citation Text", help="Paste the citation text, e.g., 'Abuseif et al. (2023)' or '(Abuseif et al., 2023)'", placeholder="e.g., Abuseif et al. (2023)") citation_url = st.text_input("Citation URL", help="Paste the hyperlink URL from the citation, e.g., 'https://www.sciencedirect.com/science/article/pii/S2772411523000046#:~:text=fragment'", placeholder="e.g., https://www.sciencedirect.com/science/article/pii/S2772411523000046#:~:text=fragment") st.subheader("SCC Index") hash_text = st.text_input("SCC Index Text", help="Paste the index text, e.g., 'Abuseif et al. (2023). '", placeholder="e.g., Abuseif et al. (2023). ") hash_url = st.text_input("SCC Index URL", help="Paste the hyperlink URL from the index, e.g., 'https://www.sciencedirect.com/science/article/pii/S2772411523000046#:~:text=metadata'", placeholder="e.g., https://www.sciencedirect.com/science/article/pii/S2772411523000046#:~:text=metadata") verify_button = st.button("Verify Citation", type="primary", use_container_width=True) if verify_button: if not all([citation_text, citation_url, hash_text, hash_url]): st.error("Please provide all fields (citation text, citation URL, SCC index text, SCC index URL) before verifying.") else: # Parse citation text author, year = parse_citation_text(citation_text) # Parse citation URL citation_base_url, citation_fragment = parse_url(citation_url) # Parse hash text scc_hash = parse_hash_text(hash_text) # Parse hash URL hash_base_url, hash_fragment = parse_url(hash_url) # Parse metadata from hash URL fragment username, task_name, date, time = parse_metadata(hash_fragment) if not all([author, year, citation_base_url, citation_fragment, scc_hash, hash_base_url, username, task_name, date, time]): st.error("Invalid input format. Ensure the citation text, URLs, and SCC index text are correctly pasted from the generated output.") elif citation_base_url != hash_base_url: st.error("The citation URL and SCC index URL must point to the same base URL.") else: # Normalize inputs by stripping whitespace citation_fragment = citation_fragment.strip() task_name = task_name.strip() # Check for potential truncation if len(citation_fragment) < 20: st.markdown("""
Warning: The citation text fragment may be truncated, which could cause verification to fail.
""", unsafe_allow_html=True) selected_citation_fragment = select_longest_segment(citation_fragment) # Recompute hash recomputed_hash = generate_citation_hash( author, year, citation_base_url, selected_citation_fragment, selected_citation_fragment, username, task_name, date, time ) if recomputed_hash == scc_hash: st.markdown("""
Authentic citation!
""", unsafe_allow_html=True) # Create DataFrame for citation details citation_data = { "Username": [username], "Task Name": [task_name], "Time": [time], "Date": [date], "URL": [citation_base_url], "Author(s) Name": [author], "Year": [year], "Annotated Text": [citation_fragment] } df = pd.DataFrame(citation_data) # Display table st.markdown("### Citation Details") st.markdown(df.to_html(classes="citation-table", index=False), unsafe_allow_html=True) # Provide download link st.markdown(get_table_download_link(df), unsafe_allow_html=True) else: st.markdown("""
Unauthentic citation
""", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # Footer st.markdown(""" """, unsafe_allow_html=True)