File size: 8,634 Bytes
cecc282
750020e
 
a76021e
750020e
8b2076c
750020e
101146a
 
750020e
 
 
 
 
a76021e
9216f55
a76021e
445c0cd
 
 
a76021e
 
750020e
 
a76021e
 
 
750020e
445c0cd
750020e
a76021e
9fcaecd
 
 
 
 
a76021e
750020e
 
 
 
 
 
a76021e
750020e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97dcbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe3eace
 
 
033a22d
 
 
 
7a72935
227499e
033a22d
227499e
6085fed
033a22d
 
 
227499e
033a22d
227499e
 
033a22d
ebd0c9c
 
 
 
 
 
 
 
ccca337
 
 
54240db
ccca337
 
 
 
 
227499e
5caf956
033a22d
fe3eace
033a22d
 
589a379
033a22d
4c8a985
fe3eace
4c8a985
 
45cbfeb
 
589a379
7a72935
 
14fafd9
bb84576
 
 
5fc7088
a76021e
eb3b113
a76021e
efdd1b6
 
 
 
959ba25
efdd1b6
38c8dad
05775e4
4c91de3
a76021e
4c91de3
a76021e
 
589a379
a76021e
 
589a379
a76021e
8e58d65
 
efdd1b6
38c8dad
45cbfeb
 
8e58d65
 
b0fe837
 
a76021e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97dcbf
8e58d65
86c4d11
7f9876a
14fafd9
7f9876a
14fafd9
e649c14
7f9876a
14fafd9
 
7f9876a
14fafd9
750020e
a76021e
 
750020e
54240db
9e9c47f
09967d8
e649c14
a76021e
e649c14
14fafd9
5fc7088
54240db
 
bb84576
14fafd9
54240db
bb84576
750020e
 
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
import spaces
import transformers
import re
from transformers import AutoTokenizer, pipeline
import torch
import html
import gradio as gr
import tempfile
import os
import pandas as pd

# Define the device
device = "cuda" if torch.cuda.is_available() else "cpu"

# Load models
editorial_model = "LLMDH/Estienne"
bibliography_model = "PleIAs/Bibliography-Formatter"
bibliography_style = "PleIAs/Bibliography-Classifier"

tokenizer = AutoTokenizer.from_pretrained(editorial_model, model_max_length=512)

editorial_classifier = pipeline(
    "token-classification", model=editorial_model, aggregation_strategy="simple", device=device
)
bibliography_classifier = pipeline(
    "token-classification", model=bibliography_model, aggregation_strategy="simple", device=device
)

style_classifier = pipeline("text-classification", model=bibliography_style, tokenizer=tokenizer, device=device)

# Helper functions
def preprocess_text(text):
    text = re.sub(r'<[^>]+>', '', text)
    text = re.sub(r'\n', ' ', text)
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

def split_text(text, max_tokens=500):
    parts = text.split("\n")
    chunks = []
    current_chunk = ""

    for part in parts:
        temp_chunk = current_chunk + "\n" + part if current_chunk else part
        num_tokens = len(tokenizer.tokenize(temp_chunk))

        if num_tokens <= max_tokens:
            current_chunk = temp_chunk
        else:
            if current_chunk:
                chunks.append(current_chunk)
            current_chunk = part

    if current_chunk:
        chunks.append(current_chunk)

    if len(chunks) == 1 and len(tokenizer.tokenize(chunks[0])) > max_tokens:
        long_text = chunks[0]
        chunks = []
        while len(tokenizer.tokenize(long_text)) > max_tokens:
            split_point = len(long_text) // 2
            while split_point < len(long_text) and not re.match(r'\s', long_text[split_point]):
                split_point += 1
            if split_point >= len(long_text):
                split_point = len(long_text) - 1
            chunks.append(long_text[:split_point].strip())
            long_text = long_text[split_point:].strip()
        if long_text:
            chunks.append(long_text)

    return chunks

def disambiguate_bibtex_ids(bibtex_entries):
    id_count = {}
    disambiguated_entries = []

    for entry in bibtex_entries:
        # Extract the current ID
        match = re.search(r'@\w+{(\w+),', entry)
        if not match:
            disambiguated_entries.append(entry)
            continue

        original_id = match.group(1)
        
        # Check if this ID has been seen before
        if original_id in id_count:
            id_count[original_id] += 1
            new_id = f"{original_id}{chr(96 + id_count[original_id])}"  # 'a', 'b', 'c', etc.
            new_entry = re.sub(r'(@\w+{)(\w+)(,)', f'\\1{new_id}\\3', entry, 1)
            disambiguated_entries.append(new_entry)
        else:
            id_count[original_id] = 0
            disambiguated_entries.append(entry)

    return disambiguated_entries

def remove_punctuation(text):
    return re.sub(r'[^\w\s]', '', text)

def extract_year(text):
    year_match = re.search(r'\b(\d{4})\b', text)
    return year_match.group(1) if year_match else None

def create_bibtex_entry(data):
    if 'journal' in data:
        entry_type = 'article'
    elif 'booktitle' in data:
        entry_type = 'inproceedings'
    else:
        entry_type = 'book'

    none_content = data.pop('none', '')
    year = extract_year(none_content)
    if year and 'year' not in data:
        data['year'] = year

    if "year" in data:
        match_year = re.search(r'(\d{4})', data['year'])
        
        if match_year:
            data['year'] = match_year.group(1)
            year = data['year']
        else:
            data.pop('year', '')

    #Pages conformity.
    if 'pages' in data:
        match = re.search(r'(\d+(-\d+)?)', data['pages'])
        if match:
            data['pages'] = match.group(1)
        else:
            data.pop('pages', '')

    author_words = data.get('author', '').split()
    first_author = author_words[0] if author_words else 'unknown'
    bibtex_id = f"{first_author}{year}" if year else first_author
    bibtex_id = remove_punctuation(bibtex_id.lower())

    bibtex = f"@{entry_type}{{{bibtex_id},\n"
    for key, value in data.items():
        if value.strip():
            if key in ['volume', 'year']:
                value = remove_punctuation(value)
            if key == 'pages':
                value = value.replace('p. ', '')
            if key != "separator":
                bibtex += f"  {key.lower()} = {{{value.strip()}}},\n"
    bibtex = bibtex.rstrip(',\n') + "\n}"
    return bibtex

def save_bibtex(bibtex_content):
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.bib') as temp_file:
        temp_file.write(bibtex_content)
    return temp_file.name

class CombinedProcessor:
    @spaces.GPU(duration=120)
    def process(self, user_message):
        #Precaution to reinforce bibliography detection.
        editorial_text = "Bibliography\n" + user_message

        #Our fix for the lack of newline in deberta
        editorial_text = re.sub("\n", " ¶ ", editorial_text)
        
        print(editorial_text)
        num_tokens = len(tokenizer.tokenize(editorial_text))
        
        batch_prompts = split_text(editorial_text, max_tokens=500) if num_tokens > 500 else [editorial_text]
    
        editorial_out = editorial_classifier(batch_prompts)
        editorial_df = pd.concat([pd.DataFrame(classification) for classification in editorial_out])
        
        # Filter out only bibliography entries
        bibliography_entries = editorial_df[editorial_df['entity_group'] == 'bibliography']['word'].tolist()
        
        bibtex_entries = []
        list_style = []
        
        for entry in bibliography_entries:
            print(entry)
            entry = re.sub(r'- ?[\n¶] ?', r'', entry)
            entry = re.sub(r' ?[\n¶] ?', r' ', entry)
            style = pd.DataFrame(style_classifier(entry, truncation=True, padding=True, top_k=1))
            list_style.append(style)
            entry = re.sub(r'\s*([;:,\.])\s*', r' \1 ', entry)
            #print(entry)
            bib_out = bibliography_classifier(entry)
            bib_df = pd.DataFrame(bib_out)
            
            bibtex_data = {}
            current_entity = None
            for _, row in bib_df.iterrows():
                entity_group = row['entity_group']
                word = row['word']
                
                if entity_group != 'None':
                    if entity_group in bibtex_data:
                        bibtex_data[entity_group] += ' ' + word
                    else:
                        bibtex_data[entity_group] = word
                    current_entity = entity_group
                else:
                    if current_entity:
                        bibtex_data[current_entity] += ' ' + word
                    else:
                        bibtex_data['None'] = bibtex_data.get('None', '') + ' ' + word
            
            bibtex_entry = create_bibtex_entry(bibtex_data)
            bibtex_entries.append(bibtex_entry)

        list_style = pd.concat(list_style)
        list_style = list_style.groupby('label')['score'].mean().sort_values(ascending=False).reset_index()
        top_style = list_style.iloc[0]['label']
        top_style_score = list_style.iloc[0]['score']

        # Create the style information string
        style_info = f"Estimated bibliographic style: {top_style} (Mean score: {top_style_score:.6f})"

        # Join BibTeX entries
        bibtex_content = "\n\n".join(bibtex_entries)

        return style_info, bibtex_content

# Create the processor instance
processor = CombinedProcessor()

# Define the Gradio interface
with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:
    gr.HTML("""<h1 style="text-align:center">Reversed Zotero</h1>""")
    text_input = gr.Textbox(label="Your unstructured bibliography", type="text", lines=10)
    text_button = gr.Button("Process Text")
    style_output = gr.Textbox(label="Bibliographic Style", lines=2)
    bibtex_output = gr.Textbox(label="BibTeX Entries", lines=15)
    
    export_button = gr.Button("Export BibTeX")
    export_output = gr.File(label="Exported BibTeX File")

    text_button.click(processor.process, inputs=text_input, outputs=[style_output, bibtex_output])
    export_button.click(save_bibtex, inputs=[bibtex_output], outputs=[export_output])

if __name__ == "__main__":
    demo.queue().launch()