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e7e2
2cc74d5
 
 
056e7e2
 
2cc74d5
056e7e2
2cc74d5
056e7e2
 
 
 
 
 
 
 
821da2d
056e7e2
 
 
821da2d
056e7e2
 
 
 
 
821da2d
056e7e2
 
 
 
 
 
 
 
821da2d
056e7e2
 
821da2d
056e7e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8d8d35
 
821da2d
f8d8d35
 
 
 
 
 
 
821da2d
056e7e2
821da2d
056e7e2
f8d8d35
 
 
 
 
 
 
821da2d
 
 
 
 
056e7e2
 
821da2d
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import streamlit as st
import pandas as pd
import urllib.request
import urllib.parse
import urllib.error
import json
import time
from typing import Dict, Optional, List
from io import StringIO

st.set_page_config(page_title="OpenAlex H-Index Lookup", page_icon="πŸ“š", layout="wide")

# Initialize session state to fix Hugging Face connection issues
if 'initialized' not in st.session_state:
    st.session_state.initialized = True
    st.rerun()

# API Configuration
BASE_URL = "https://api.openalex.org"
RATE_LIMIT_DELAY = 0.15
POLITE_EMAIL = "halozen@pm.me"

def get_author_by_id(author_id: str) -> Optional[Dict]:
    """Fetch author information by OpenAlex ID."""
    if not author_id.upper().startswith('A'):
        author_id = f"A{author_id}"

    params = urllib.parse.urlencode({'mailto': POLITE_EMAIL})
    url = f"{BASE_URL}/authors/{author_id}?{params}"

    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            if response.status == 200:
                data = response.read()
                return json.loads(data.decode('utf-8'))
    except Exception as e:
        st.warning(f"Error fetching author {author_id}: {str(e)}")
    return None

def search_author_by_name(name: str, affiliation_hint: str = None, max_results: int = 5) -> List[Dict]:
    """Search for authors by name, using affiliation hint to re-rank results."""
    params = {
        'search': name,
        'per-page': max_results * 4,
        'mailto': POLITE_EMAIL
    }

    url = f"{BASE_URL}/authors?{urllib.parse.urlencode(params)}"

    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            if response.status == 200:
                data = response.read()
                json_data = json.loads(data.decode('utf-8'))
                results = json_data.get('results', [])

                def sort_key(author):
                    has_orcid = 1 if author.get('orcid') else 0
                    works_count = author.get('works_count', 0)

                    affiliation_match = 0
                    if affiliation_hint:
                        hint_lower = affiliation_hint.lower()

                        last_institutions = author.get('last_known_institutions', [])
                        for inst in last_institutions:
                            if inst:
                                inst_name = inst.get('display_name', '') or ''
                                country = inst.get('country_code', '') or ''
                                inst_name_lower = inst_name.lower()
                                country_lower = country.lower()
                                if hint_lower in inst_name_lower or hint_lower in country_lower or inst_name_lower in hint_lower:
                                    affiliation_match = 1
                                    break

                        if affiliation_match == 0:
                            all_affiliations = author.get('affiliations', [])
                            for aff in all_affiliations:
                                if aff:
                                    inst = aff.get('institution', {}) or {}
                                    inst_name = inst.get('display_name', '') or ''
                                    country = inst.get('country_code', '') or ''
                                    inst_name_lower = inst_name.lower()
                                    country_lower = country.lower()
                                    if hint_lower in inst_name_lower or hint_lower in country_lower or inst_name_lower in hint_lower:
                                        affiliation_match = 1
                                        break

                    return (affiliation_match, has_orcid, works_count)

                results.sort(key=sort_key, reverse=True)
                return results[:max_results]
    except Exception as e:
        st.warning(f"Error searching {name}: {str(e)}")
    return []

def get_top_journals(author_data: Dict, max_journals: int = 5) -> str:
    """Get the top 5 journals where the author has published most frequently."""
    if not author_data or 'id' not in author_data:
        return "N/A"

    author_id = author_data['id']

    params = urllib.parse.urlencode({
        'filter': f'authorships.author.id:{author_id},primary_location.source.type:journal',
        'group_by': 'primary_location.source.id',
        'mailto': POLITE_EMAIL
    })
    url = f"{BASE_URL}/works?{params}"

    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            if response.status == 200:
                data = response.read()
                json_data = json.loads(data.decode('utf-8'))
                group_by_results = json_data.get('group_by', [])

                journals = []
                for item in group_by_results[:max_journals]:
                    key_display_name = item.get('key_display_name')
                    count = item.get('count', 0)
                    if key_display_name and key_display_name != 'unknown':
                        journals.append(f"{key_display_name} ({count})")

                return ", ".join(journals) if journals else "N/A"
    except Exception as e:
        st.warning(f"Error fetching journals: {str(e)}")
    return "N/A"

def detect_input_type(input_str: str) -> tuple:
    """
    Detect if input is a name, ORCID, or OpenAlex ID.
    Returns: (type, cleaned_value) where type is 'name', 'orcid', or 'openalex_id'
    """
    input_str = input_str.strip()
    
    # Check for ORCID format: 0000-0000-0000-0000 or URLs
    if 'orcid.org/' in input_str.lower():
        # Extract ORCID from URL
        orcid = input_str.split('orcid.org/')[-1].strip('/')
        return ('orcid', orcid)
    elif input_str.replace('-', '').isdigit() and len(input_str.replace('-', '')) == 16:
        # Raw ORCID format: 0000-0002-1825-0097
        return ('orcid', input_str)
    
    # Check for OpenAlex ID format: A1234567890 or URLs
    if 'openalex.org/A' in input_str or 'openalex.org/authors/A' in input_str:
        # Extract ID from URL
        openalex_id = input_str.split('/')[-1].strip()
        if openalex_id.startswith('A'):
            return ('openalex_id', openalex_id)
    elif input_str.upper().startswith('A') and len(input_str) > 5 and input_str[1:].isdigit():
        # Raw OpenAlex ID format: A5023888391
        return ('openalex_id', input_str.upper())
    
    # Otherwise treat as a name
    return ('name', input_str)


def get_author_by_orcid(orcid: str) -> Optional[Dict]:
    """Fetch author information by ORCID."""
    # Clean ORCID
    orcid = orcid.replace('https://orcid.org/', '').replace('http://orcid.org/', '').strip('/')
    
    params = urllib.parse.urlencode({
        'filter': f'orcid:{orcid}',
        'mailto': POLITE_EMAIL
    })
    url = f"{BASE_URL}/authors?{params}"

    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            if response.status == 200:
                data = response.read()
                json_data = json.loads(data.decode('utf-8'))
                results = json_data.get('results', [])
                if results:
                    return results[0]
    except Exception as e:
        st.warning(f"Error fetching ORCID {orcid}: {str(e)}")
    return None


def process_author(name_or_id: str, hint: str = None) -> Dict:
    """
    Process a single author and return their data.
    Accepts: author name, ORCID, or OpenAlex ID
    """
    # Detect what type of input we have
    input_type, cleaned_input = detect_input_type(name_or_id)
    
    author = None
    
    if input_type == 'orcid':
        # Look up by ORCID
        author = get_author_by_orcid(cleaned_input)
        if author:
            display_name = author.get('display_name', name_or_id)
        else:
            return {
                'Name': name_or_id,
                'ORCID': cleaned_input,
                'H-Index': None,
                'Works Count': None,
                'Cited By Count': None,
                '2yr Mean Citedness': None,
                'i10 Index': None,
                'Top Topic': None,
                'Top Topic Count': None,
                'Top 5 Journals': None,
                'Last Known Institution': None,
                'Warning': f'ORCID not found: {cleaned_input}'
            }
    
    elif input_type == 'openalex_id':
        # Look up by OpenAlex ID
        author = get_author_by_id(cleaned_input)
        if author:
            display_name = author.get('display_name', name_or_id)
        else:
            return {
                'Name': name_or_id,
                'ORCID': None,
                'H-Index': None,
                'Works Count': None,
                'Cited By Count': None,
                '2yr Mean Citedness': None,
                'i10 Index': None,
                'Top Topic': None,
                'Top Topic Count': None,
                'Top 5 Journals': None,
                'Last Known Institution': None,
                'Warning': f'OpenAlex ID not found: {cleaned_input}'
            }
    
    else:  # input_type == 'name'
        # Original name search logic
        results = search_author_by_name(cleaned_input, affiliation_hint=hint, max_results=3)
        
        if not results:
            return {
                'Name': cleaned_input,
                'ORCID': None,
                'H-Index': None,
                'Works Count': None,
                'Cited By Count': None,
                '2yr Mean Citedness': None,
                'i10 Index': None,
                'Top Topic': None,
                'Top Topic Count': None,
                'Top 5 Journals': None,
                'Last Known Institution': None,
                'Warning': 'Not found'
            }
        
        author = results[0]
        display_name = author.get('display_name', cleaned_input)
        
        # Check for disambiguation issues (only for name searches)
        warning = ""
        if len(results) > 1:
            if not author.get('orcid'):
                warning = "⚠️ Multiple matches, no ORCID"
            else:
                similar_names = [r.get('display_name', '') for r in results[1:]
                               if r.get('display_name', '').lower() == display_name.lower()]
                if similar_names:
                    warning = f"⚠️ {len(similar_names)+1} exact name matches"

        if display_name.lower() != cleaned_input.lower():
            if warning:
                warning += f" | Matched to: {display_name}"
            else:
                warning = f"⚠️ Matched to: {display_name}"

    # Extract data (same for all input types)
    if not author:
        return {
            'Name': name_or_id,
            'ORCID': None,
            'H-Index': None,
            'Works Count': None,
            'Cited By Count': None,
            '2yr Mean Citedness': None,
            'i10 Index': None,
            'Top Topic': None,
            'Top Topic Count': None,
            'Top 5 Journals': None,
            'Last Known Institution': None,
            'Warning': 'Not found'
        }
    
    h_index = author.get('summary_stats', {}).get('h_index')
    works_count = author.get('works_count')
    cited_by_count = author.get('cited_by_count')
    summary_stats = author.get('summary_stats', {})
    two_yr_mean = summary_stats.get('2yr_mean_citedness')
    i10_index = summary_stats.get('i10_index')

    orcid = author.get('orcid', '')

    topics = author.get('topics', [])
    top_topic_name = topics[0].get('display_name') if topics else None
    top_topic_count = topics[0].get('count') if topics else None

    top_journals = get_top_journals(author)

    last_institutions = author.get('last_known_institutions', [])
    institution_names = [inst.get('display_name', '') for inst in last_institutions] if last_institutions else []
    last_institution = ", ".join(institution_names) if institution_names else None

    # Use display_name if we found it, otherwise use original input
    final_name = display_name if 'display_name' in locals() else name_or_id

    return {
        'Name': final_name,
        'ORCID': orcid,
        'H-Index': h_index,
        'Works Count': works_count,
        'Cited By Count': cited_by_count,
        '2yr Mean Citedness': round(two_yr_mean, 2) if two_yr_mean else None,
        'i10 Index': i10_index,
        'Top Topic': top_topic_name,
        'Top Topic Count': top_topic_count,
        'Top 5 Journals': top_journals,
        'Last Known Institution': last_institution,
        'Warning': warning if input_type == 'name' and warning else None
    }

def process_dataframe(df: pd.DataFrame) -> pd.DataFrame:
    """Process a dataframe of authors and return results."""
    # Add Institution_Hint column if it doesn't exist
    if 'Institution_Hint' not in df.columns:
        df['Institution_Hint'] = None
    
    results = []
    progress_bar = st.progress(0)
    status_text = st.empty()

    for idx, row in df.iterrows():
        name = row['Name']
        hint = row.get('Institution_Hint')

        if pd.notna(name) and str(name).strip():
            status_text.text(f"Processing {idx+1}/{len(df)}: {name}")

            result = process_author(
                str(name).strip(),
                str(hint).strip() if pd.notna(hint) else None
            )
            results.append(result)

            # Rate limiting
            time.sleep(RATE_LIMIT_DELAY)

        progress_bar.progress((idx + 1) / len(df))

    status_text.text("βœ… Processing complete!")
    return pd.DataFrame(results)

def display_results(results_df: pd.DataFrame):
    """Display results with statistics and download button."""
    st.subheader("πŸ“Š Results")
    st.dataframe(results_df, use_container_width=True)

    # Statistics
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        found = results_df['H-Index'].notna().sum()
        st.metric("Found", f"{found}/{len(results_df)}")
    with col2:
        avg_h = results_df['H-Index'].mean()
        st.metric("Avg H-Index", f"{avg_h:.1f}" if pd.notna(avg_h) else "N/A")
    with col3:
        with_orcid = results_df['ORCID'].notna().sum()
        st.metric("With ORCID", f"{with_orcid}/{len(results_df)}")
    with col4:
        warnings = results_df['Warning'].notna().sum()
        st.metric("Warnings", warnings)

    # Download button
    csv = results_df.to_csv(index=False)
    st.download_button(
        label="πŸ“₯ Download Results as CSV",
        data=csv,
        file_name="openalex_results.csv",
        mime="text/csv",
        type="primary"
    )

# ============================================================================
# MAIN APP
# ============================================================================

st.title("πŸ“š OpenAlex H-Index Lookup Tool")
st.markdown("""
Batch lookup h-indices and publication metrics for researchers using the OpenAlex API.
""")

# Sidebar
with st.sidebar:
    st.header("ℹ️ How to Use")
    st.markdown("""
    1. **Choose input method:**
       - Upload CSV file
       - Paste CSV data
       - Run test with sample data
    2. **CSV format:**
       - `Name` column (required) - accepts:
         - Author names (e.g., "John Smith")
         - ORCID IDs (e.g., "0000-0002-1825-0097")
         - OpenAlex IDs (e.g., "A5023888391")
       - `Institution_Hint` column (optional)
    3. **Click Process** to retrieve data
    4. **Download** results as CSV
    
    **Tips:**
    - Mix names and IDs in the same file!
    - Institution hints improve name matching
    - ORCIDs and OpenAlex IDs = 100% accurate
    - Processing ~6-7 authors per second
    """)

    st.divider()
    st.markdown("**Data source:** [OpenAlex](https://openalex.org)")
    st.markdown("**Rate limit:** ~0.15s per author")

# Test Mode Button
st.subheader("πŸ§ͺ Quick Test")
if st.button("Run with Sample Data", help="Test with Einstein, Curie, and Newton"):
    test_data = pd.DataFrame({
        'Name': ['Albert Einstein', 'Marie Curie', 'Isaac Newton'],
        'Institution_Hint': ['Princeton', 'Paris', 'Cambridge']
    })
    
    with st.spinner("Processing sample data..."):
        results_df = process_dataframe(test_data)
    
    display_results(results_df)

st.divider()

# Main Input Section with Tabs
st.subheader("πŸ“‹ Input Your Data")

tab1, tab2, tab3 = st.tabs(["πŸ“€ Upload CSV", "πŸ“ Paste CSV", "πŸ“₯ Download Template"])

with tab1:
    st.markdown("Upload a CSV file with author names:")
    uploaded_file = st.file_uploader(
        "Choose a CSV file", 
        type=['csv'],
        help="CSV must have a 'Name' column. 'Institution_Hint' is optional.",
        key="csv_uploader"
    )

    if uploaded_file is not None:
        try:
            df = pd.read_csv(uploaded_file)

            # Validate columns
            if 'Name' not in df.columns:
                st.error("❌ CSV must have a 'Name' column")
            else:
                st.success(f"βœ… Loaded {len(df)} names")

                # Preview
                with st.expander("πŸ“‹ Preview uploaded data"):
                    st.dataframe(df.head(10))

                # Process button
                if st.button("πŸš€ Process Authors", type="primary", key="process_upload"):
                    results_df = process_dataframe(df)
                    display_results(results_df)

        except Exception as e:
            st.error(f"Error reading file: {str(e)}")

with tab2:
    st.markdown("Paste CSV data directly (useful if file upload doesn't work):")
    
    csv_text = st.text_area(
        "Paste your CSV data here:", 
        height=200,
        placeholder="Name,Institution_Hint\nAlbert Einstein,Princeton\nMarie Curie,Paris\nJohn Smith,MIT",
        help="Include headers in first row. Separate columns with commas."
    )
    
    if st.button("πŸš€ Process Pasted Data", type="primary", key="process_paste") and csv_text:
        try:
            df = pd.read_csv(StringIO(csv_text))
            
            # Validate columns
            if 'Name' not in df.columns:
                st.error("❌ CSV must have a 'Name' column")
            else:
                st.success(f"βœ… Parsed {len(df)} names")
                
                # Preview
                with st.expander("πŸ“‹ Preview pasted data"):
                    st.dataframe(df.head(10))
                
                # Process
                results_df = process_dataframe(df)
                display_results(results_df)
                
        except Exception as e:
            st.error(f"Error parsing CSV: {str(e)}")
            st.info("Make sure your data is in valid CSV format with headers.")

with tab3:
    st.markdown("Download a template CSV to get started:")
    
    st.info("πŸ’‘ **Pro tip:** You can mix names, ORCIDs, and OpenAlex IDs in the same file!")
    
    example_df = pd.DataFrame({
        'Name': [
            'Albert Einstein', 
            '0000-0002-1825-0097',  # Example ORCID
            'A5023888391',  # Example OpenAlex ID
            'Marie Curie'
        ],
        'Institution_Hint': ['Princeton', 'Optional', 'Optional', 'Paris']
    })
    
    st.dataframe(example_df)
    
    st.markdown("""
    **Accepted formats in Name column:**
    - Regular name: `John Smith`
    - ORCID: `0000-0002-1825-0097` or `https://orcid.org/0000-0002-1825-0097`
    - OpenAlex ID: `A5023888391` or `https://openalex.org/A5023888391`
    """)
    
    template_csv = example_df.to_csv(index=False)
    st.download_button(
        label="πŸ“₯ Download Template CSV",
        data=template_csv,
        file_name="openalex_template.csv",
        mime="text/csv",
        help="Download this template and fill in with your data"
    )